C# 根据绑定项更改按钮的颜色
我有一个绑定到类的按钮的xaml。我向类中添加了另一个属性,如果该属性的值大于零,则希望按钮的背景色为黄色C# 根据绑定项更改按钮的颜色,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,我有一个绑定到类的按钮的xaml。我向类中添加了另一个属性,如果该属性的值大于零,则希望按钮的背景色为黄色 <local:TileView x:Key="Button_Available_View"> <local:TileView.ItemTemplate> <DataTemplate> <Grid> <Button Command="command:Command_Button
<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>
我该如何修改它?应该给你一些很好的例子。它的本质是您需要使用样式触发器来确定您的背景应该是哪种颜色。最简单的方法是在绑定上创建一个
IValueConverter
,将属性的值转换为颜色,或者在基于值设置颜色的项目样式中使用DataTrigger
。必须将按钮的前景属性绑定到视图模型的属性。然后可以使用转换器将值转换为颜色
转换器如下所示:
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" />
当然,您必须将转换器作为静态资源添加到页面中 到目前为止,我已经想到了:
Background="{Binding Path=BackColor}"
然后在代码隐藏绑定类中:
public Brush BackColor
{
get
{
if (SimilarHits > 0) return Brushes.Yellow;
return Brushes.WhiteSmoke;
}
}
我不懂WPF,看来你得写二十行才能说“你好,世界”
将此标记为答案-最少的代码量以获得所需的结果。将颜色绑定到属性,然后需要转换器返回颜色。实际上需要绑定背景而不是前景。我无意中否决了您的答案。如果你愿意改变你的答案,我可以取消反对票。那么你可以结合背景。我将在答案中编辑该值,以便您可以删除否决票:)感谢您的响应,但我得到错误:
“System.Windows.Data.BindingExpression”值不能分配给对象“System.Windows.Controls.Button”的属性“Background”。指定的强制转换无效。
我尝试了画笔对象的系统.Drawing
和系统.Windows.Media
,也尝试了“黄色”
和“蓝色”
,但均无效。您应该使用System.Windows.Media.笔刷。您是否正在编写WPF应用程序以及您的目标版本?它在我的机器上运行得很好。