根据绑定项目更改按钮的颜色
问题描述:
我对绑定到类的按钮具有此xaml。我向该类中添加了另一个属性,并且如果该属性的值大于零,则该按钮的背景颜色为黄色。根据绑定项目更改按钮的颜色
<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>
我该如何修改?
答
到目前为止,我想出了:
Background="{Binding Path=BackColor}"
然后在后面绑定类代码:
public Brush BackColor
{
get
{
if (SimilarHits > 0) return Brushes.Yellow;
return Brushes.WhiteSmoke;
}
}
我不明白WPF,看来你得写20行说"hello world"
。
标记此答案 - 获得所需结果的代码量最少。
答
最简单的方法是在绑定上创建一个IValueConverter
,将属性的值转换为颜色,或者在您的项目样式中使用DataTrigger
来设置基于值的颜色?
+0
我更喜欢datatrigger,因为它不需要隐藏代码。 – mydogisbox 2012-02-10 21:44:17
答
您必须将按钮的Foreground属性绑定到视图模型的属性。然后,您可以使用转换器将该值转换为彩色。
转换器应该是这样的:
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();
}
}
编辑:更新绑定的背景而不是前景 的XAML将是XAML:
<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" />
当然,你必须将转换器作为静态资源添加到页面。
将颜色绑定到属性,但然后需要转换器才能返回颜色。 – Paparazzi 2012-02-10 21:36:45