我有一个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>
我该如何修改?
答案 0 :(得分:2)
This应该给你一些很好的例子来解决问题。它的本质是你需要使用样式触发器来确定你的背景应该是哪种颜色。
答案 1 :(得分:1)
您必须将按钮的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" />
当然,您必须将转换器添加为页面的静态资源。
答案 2 :(得分:0)
最简单的方法是在绑定上创建IValueConverter
,将属性的值转换为颜色,或者在项目样式中使用DataTrigger
设置基于颜色的颜色价值?
答案 3 :(得分:0)
到目前为止,我已经提出:
Background="{Binding Path=BackColor}"
然后在绑定类后面的代码中:
public Brush BackColor
{
get
{
if (SimilarHits > 0) return Brushes.Yellow;
return Brushes.WhiteSmoke;
}
}
我不懂WPF,你似乎要写二十行来说"hello world"
。
将答案标记为答案 - 获得所需结果的代码量最少。