How can change the fill color of an object I\'m being to in my mvvm setup using xaml in wpf. I want to change the fill color to red when the attribute being bound to is set to
First of all you don't need any Binding for what you are trying to do. DataTrigger is enough. In the example below IsCyan is a boolean property of ViewModel. But Background of TextBlock is not bound at all.
<TextBlock Text="Inside content">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding IsCyan}" Value="True">
<Setter Property="Background" Value="DarkCyan"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsCyan}" Value="False">
<Setter Property="Background" Value="DarkGoldenrod"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
But if at all you need Binding, solution by the user benPearce to use Converter is the way to go.
You need to use an IValueConverter on the binding.
BackgroundColor="{Binding Path=IsRound, Converter={StaticResource BoolToFillColorConverter}}"
public class BoolToFillColorConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool b;
if (bool.TryParse(value, out b))
{
if (b) return Red
else return Blue;
}
else
{
return SomeDefaultColour;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}