Reputation: 1341
I have a WPF project.
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. 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. It's also not working. Where did I miss something?
Upvotes: 0
Views: 242
Reputation: 169220
Your converter should return System.Windows.Media.Brushes.Green
instead of 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
.
Upvotes: 3