通过WPF中的MVVM模式更改按钮背景颜色

Yog*_*esh 17 wpf mvvm-light

我在WPF中使用MVVM灯.我想通过ViewModel根据某些特定条件设置按钮背景颜色.请建议一些方法来获得它.谢谢

alm*_*ori 28

你可以将Background绑定到viewmodel上的一个属性,诀窍是使用IValueConverter返回一个你需要的颜色的画笔,这是一个将一个布局值从viewmodel转换为一个颜色的例子

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

带有绑定表达式

    "{Binding Reviewed, Converter={StaticResource BoolToColorConverter}}"
Run Code Online (Sandbox Code Playgroud)


H.B*_*.B. 25

使用触发器:

<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>
Run Code Online (Sandbox Code Playgroud)

[ 关于说明 ]


在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;
Run Code Online (Sandbox Code Playgroud)

那你就绑定了Background.