[英]Binding color to bool using converter does not get updated
I have a WPF project.我有一个 WPF 项目。
I want to have a brush of a border depending on a bool value of my viewmodel.我想根据我的视图模型的布尔值画一个边框。 I wrote a binding to a bool property, which gets updated, and have a special converter from bool to some brush.
我写了一个到 bool 属性的绑定,该属性得到更新,并且有一个从 bool 到某个画笔的特殊转换器。 everything gets call right, but the color does not appear.
一切都正确,但颜色没有出现。
I've made a sample application to show the issue:我制作了一个示例应用程序来显示该问题:
<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>
My converter looks like this:我的转换器如下所示:
[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;
}
//...
}
This is how it looks like in running application:这是它在运行应用程序时的样子:
I also tried other colors, like text block background.我还尝试了其他 colors,例如文本块背景。 It's also not working.
它也不起作用。 Where did I miss something?
我在哪里错过了什么?
Your converter should return System.Windows.Media.Brushes.Green
instead of Colors.Green
:您的转换器应返回
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;
}
The BorderBrush
can only be set to a Brush
and not to a Color
. BorderBrush
只能设置为Brush
而不能设置为Color
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.