【问题标题】:Change Button Background color through MVVM pattern in WPF通过 WPF 中的 MVVM 模式更改按钮背景颜色
【发布时间】:2011-09-07 06:39:47
【问题描述】:

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

【问题讨论】:

    标签: wpf mvvm-light


    【解决方案1】:

    您可以将控件的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 是您的布尔视图模型属性。

    【讨论】:

    • 您是否需要将 Coverter Key 添加到资源中?
    【解决方案2】:

    使用触发器:

    <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>
    

    Explanation of the comment.


    在视图模型 (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

    【讨论】:

    • 在使用 wpf 时这是一种非常好的方法,如果您正在寻找可以移植到 silverlight 的代码,您可能还需要用于触发语义的表达式 SDK
    猜你喜欢
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2021-06-22
    • 2015-04-03
    相关资源
    最近更新 更多