我正在使用MVVM light和WPF。我想通过ViewModel根据某些特定条件设置按钮的背景颜色。请提供一些实现方式。谢谢。
我正在使用MVVM light和WPF。我想通过ViewModel根据某些特定条件设置按钮的背景颜色。请提供一些实现方式。谢谢。
你可以将控件的Background
绑定到viewmodel上的一个属性,技巧在于使用IValueConverter
来返回所需颜色的Brush
。这是一个示例,它将从viewmodel转换布尔值为颜色:
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
。
private SolidColorBrush _penBrush;
public SolidColorBrush PenBrush { get { return _penBrush; } set { SetPropertyChanged(ref _penBrush, value, "PenBrush"); } }
private Color _penColor;
public Color PenColor { get { return _penColor; } set { SetPropertyChanged(ref _penColor, value, "PenColor"); PenBrush = new SolidColorBrush(_penColor); } }
使用以下XAML代码:
<Button Background="{Binding PenBrush}"></Button>