实现功能,当CheckBox勾选时,字体为红色,否则为绿色
好处:可以将xaml代码和后台代码逻辑分离在某些情况下会非常方便
上代码:
<StackPanel>
<StackPanel.Resources>
<local:BoolToColor x:Key="boolToColor"></local:BoolToColor>
</StackPanel.Resources>
<CheckBox Content="check" Name="checkbox" Foreground="{Binding ElementName=checkbox,Path=IsChecked,Converter={StaticResource boolToColor}}"></CheckBox>
</StackPanel>
后台代码:
[ValueConversion(typeof(bool), typeof(string))]
public class BoolToColor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if((bool)value)
{
return "Red";
}
return "Green";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException("[Converter_IsConnected2Color] Cannot Convert Back.");
}
}