通过 WPF 中的 MVVM 模式更改按钮背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7329812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change Button Background color through MVVM pattern in WPF
提问by Yogesh
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
我在 WPF 中使用 MVVM 灯。我想通过 ViewModel 根据某些特定条件设置按钮背景颜色。请建议一些方法来获得它。谢谢
回答by almog.ori
you could bind the Background to a property on the viewmodel the trick is to use a IValueConverter to return a brush with the color your require, heres an example that converts a boolean value from the viewmodel to a color
您可以将背景绑定到视图模型上的属性,诀窍是使用 IValueConverter 返回带有您需要的颜色的画笔,这是将布尔值从视图模型转换为颜色的示例
public class BoolToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return new SolidColorBrush(Colors.Transparent);
}
return System.Convert.ToBoolean(value) ?
new SolidColorBrush(Colors.Red)
: new SolidColorBrush(Colors.Transparent);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
with a binding expression like
带有绑定表达式,例如
"{Binding Reviewed, Converter={StaticResource BoolToColorConverter}}"
回答by H.B.
Using triggers:
使用触发器:
<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>
[关于注释]
In MVVM you can also often handle this in the view-model via get-only properties as well, e.g.
在 MVVM 中,您也可以经常通过 get-only 属性在视图模型中处理此问题,例如
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;
Then you just bind to Background
.
然后你只需绑定到Background
.