通过WPF中的MVVM模式更改按钮背景颜色 [英] Change Button Background color through MVVM pattern in WPF
本文介绍了通过WPF中的MVVM模式更改按钮背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将MVVM灯与WPF一起使用.我想通过ViewModel根据某些特定条件设置按钮背景色.请提出一些获取方法.谢谢
I am using MVVM light with WPF. I want to set button background color based on some specific condition through ViewModel. Kindly suggest some way to get it. Thanks
推荐答案
使用触发器:
<Button>
<Button.Style>
<Style TargetType="Button">
<!-- Set the default value here (if any)
if you set it directly on the button that will override the trigger -->
<Setter Property="Background" Value="LightGreen" />
<Style.Triggers>
<DataTrigger Binding="{Binding SomeConditionalProperty}"
Value="True">
<Setter Property="Background" Value="Pink" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
[关于注释]
在MVVM中,您通常还可以通过仅获取属性(例如
In MVVM you can also often handle this in the view-model via get-only properties as well, e.g.
public bool SomeConditionalProperty
{
get { /*...*/ }
set
{
//...
OnPropertyChanged(nameof(SomeConditionalProperty));
//Because Background is dependent on this property.
OnPropertyChanged(nameof(Background));
}
}
public Brush Background =>
SomeConditinalProperty ? Brushes.Pink : Brushes.LightGreen;
然后您只需绑定到Background
.
这篇关于通过WPF中的MVVM模式更改按钮背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文