[英]Why does bool work for visibility without a converter when using traditional binding
[英]Binding color to bool using converter does not get updated
我有一个 WPF 项目。
我想根据我的视图模型的布尔值画一个边框。 我写了一个到 bool 属性的绑定,该属性得到更新,并且有一个从 bool 到某个画笔的特殊转换器。 一切都正确,但颜色没有出现。
我制作了一个示例应用程序来显示该问题:
<StackPanel>
<Border BorderThickness="3" BorderBrush="{Binding ElementName=OnOffSwitch, Path=IsChecked, Converter={StaticResource BoolToGreen}, Mode=OneWay}">
<TextBlock >
<Run Text="The option is " />
<Run Text="{Binding ElementName=OnOffSwitch, Path=IsChecked, Mode=OneWay}" />
<Run Text=" Color should be " />
<Run Text="{Binding ElementName=OnOffSwitch, Path=IsChecked, Mode=OneWay, Converter={StaticResource BoolToGreen}}" />
</TextBlock>
</Border>
<CheckBox x:Name="OnOffSwitch" Content="Green" IsChecked="{Binding OnOff}" />
</StackPanel>
我的转换器如下所示:
[ValueConversion(typeof(bool), typeof(Brush))]
public class BoolToGreenColorConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return (bool)value ? System.Windows.Media.Colors.Green : System.Windows.Media.Colors.Red;
}
//...
}
我还尝试了其他 colors,例如文本块背景。 它也不起作用。 我在哪里错过了什么?
您的转换器应返回System.Windows.Media.Brushes.Green
而不是Colors.Green
:
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return (bool)value ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red;
}
BorderBrush
只能设置为Brush
而不能设置为Color
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.