【发布时间】:2011-09-07 06:39:47
【问题描述】:
我在 WPF 中使用 MVVM 灯。我想通过 ViewModel 根据某些特定条件设置按钮背景颜色。请建议一些方法来获得它。谢谢
【问题讨论】:
标签: wpf mvvm-light
我在 WPF 中使用 MVVM 灯。我想通过 ViewModel 根据某些特定条件设置按钮背景颜色。请建议一些方法来获得它。谢谢
【问题讨论】:
标签: wpf mvvm-light
您可以将控件的Background 绑定到视图模型上的属性,诀窍是使用IValueConverter 返回具有所需颜色的Brush。这是一个将视图模型中的布尔值转换为颜色的示例:
public class BoolToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Brushes.Transparent;
return Convert.ToBoolean(value)
? Brushes.Red
: Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
使用类似的绑定表达式
"{Binding Reviewed, Converter={StaticResource BoolToBrushConverter}}"
Reviewed 是您的布尔视图模型属性。
【讨论】:
使用触发器:
<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) 中使用依赖属性:
public bool SomeConditionalProperty
{
get { /*...*/ }
set
{
//...
OnPropertyChanged(nameof(SomeConditionalProperty));
//Because Background is dependent on this property.
OnPropertyChanged(nameof(Background));
}
}
public Brush Background =>
SomeConditionalProperty ? Brushes.Pink : Brushes.LightGreen;
然后你只需绑定到Background。
【讨论】: