Reputation: 11955
I have this xaml for a button that is bound to a class. I've added another property to the class and want the background color of the button to be yellow if the value of the property is greater than zero.
<local:TileView x:Key="Button_Available_View">
<local:TileView.ItemTemplate>
<DataTemplate>
<Grid>
<Button
Command="command:Command_Button_AvailableTags.Command"
CommandParameter="{Binding Path=Name}"
Content="{Binding Path=Name}"
Tag="{Binding Path=Name}"
HorizontalAlignment="Stretch"
Padding="3,1,3,1"
Margin="0"
HorizontalContentAlignment="Center"
/>
</Grid>
</DataTemplate>
</local:TileView.ItemTemplate>
</local:TileView>
How would I modify this?
Upvotes: 1
Views: 1964
Reputation: 11955
So far I've come up with:
Background="{Binding Path=BackColor}"
And then in the code behind binding class:
public Brush BackColor
{
get
{
if (SimilarHits > 0) return Brushes.Yellow;
return Brushes.WhiteSmoke;
}
}
I don't understand WPF, it seems you have to write twenty lines to say "hello world"
.
Marking this the answer - least amount of code to get the result desired.
Upvotes: 0
Reputation: 2364
You have to bind the Foreground property of the button to the property of the view model. Then you can use a converter to convert the value to color.
The converter would look like this:
public class TextToColorConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (((int)value) > 0)
return Brushes.Yellow;
else
// for default value
return Brushes.Blue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// no need to implement it
throw new NotImplementedException();
}
}
Edited: Updated the xaml to bind the background instead of the Foreground The xaml would be:
<Button
Background="{Binding Path=Property, Converter={StaticResource textToColorConverter}}" Command="command:Command_Button_AvailableTags.Command" CommandParameter="{Binding Path=Name}" Content="{Binding Path=Name}" Tag="{Binding Path=Name}" HorizontalAlignment="Stretch" Padding="3,1,3,1" Margin="0" HorizontalContentAlignment="Center" />
Of course, you have to add the converter as a static resource to the page.
Upvotes: 1
Reputation: 25116
The simplest way would be to create either an IValueConverter
on your binding that converts the value of the property to a color, or use a DataTrigger
in the style of your item that sets the color based on value?
Upvotes: 0