IValueConverter
Convert:数据绑定引擎在将值从绑定源传播到绑定目标时调用此方法。
ConvertBack:数据绑定引擎在将值从绑定目标传播到绑定源时调用此方法。
<TextBox x:Name="colorText" Text="1" BorderBrush="Gray" BorderThickness="2" Width="200" Grid.Row="1"/>
<Button x:Name="testBtn" Content="测试" Width="100" Grid.Row="3" FontSize="25" Foreground="{Binding Path=Text,ElementName=colorText,Converter={StaticResource sujConverter},Mode=TwoWay}"/>
<!--这样写,走框架-->
private void Button_Click(object sender, RoutedEventArgs e)
{
testBtn.Foreground = ((Button)sender).Foreground;
}
//这样写,先ConvertBack,再Convert
//(先用ConvertBack把{#FF008000}(绿色)转化为2,再用Convert把2转为SolidColorBrush颜色给foerground)
public class SujianConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || "".Equals(value.ToString())) return new SolidColorBrush(Colors.Black);
int colorValue = System.Convert.ToInt32(value);
switch (colorValue)
{
case 1:
return new SolidColorBrush(Colors.Red);
case 2:
return new SolidColorBrush(Colors.Green);
case 3:
return new SolidColorBrush(Colors.Blue);
}
return new SolidColorBrush(Colors.LawnGreen);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
SolidColorBrush sb = (SolidColorBrush)value;
Color c = sb.Color;
if (c == Colors.Red)
{
return 1;
}
else if (c == Colors.Green)
{
return 2;
}
else if (c == Colors.Blue)
{
return 3;
}
return 0;
}
标签:return,object,SolidColorBrush,value,Colors,ConvertBack,作用
From: https://www.cnblogs.com/sj1050966063/p/18001992