MVVM单击更改网格的背景颜色 [英] MVVM changing grid's background color on click

查看:110
本文介绍了MVVM单击更改网格的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVVM模式的真正初学者.我正在尝试更改按钮单击时网格的背景.我有一个xaml,其中包含一个包含按钮的网格,以及一个ViewModel .cs,我想从该位置在单击按钮时更改网格的背景.直到那里,我单击鼠标后便成功显示了一个MessageBox.

I'm a true beginner in MVVM pattern. I'm trying to change the backgound of a grid on button's click. I have a xaml with a grid containing a button, and a ViewModel .cs from where i want to change the grid's background on button's click. Until there i just succeed to show up a MessageBox when i clicked...

.xaml代码:

<Window x:Class="WpfSimple.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfSimple"
    Title="MainWindow" Height="150" Width="370">
<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>
    <Grid>
    <Button Content="Click" 
            Height="23" 
            HorizontalAlignment="Left"
            Background="Gray"
            Margin="75.944,47.465,0,0" 
            Name="btnClick" 
            VerticalAlignment="Top" 
            Width="203"
            Command="{Binding ButtonCommand}"/>
        <!--What is necessary to add for changing grid color ? Commandparameter ?-->
</Grid>

MainWindowViewModel.cs代码:

MainWindowViewModel.cs code:

namespace WpfSimple
{
    class MainWindowViewModel
    {
        private ICommand m_ButtonCommand;
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }

        public MainWindowViewModel()
        {
            ButtonCommand=new RelayCommand(new Action<object>(ChangeBgColor));
        }

        public void ChangeBgColor(object obj)
        {
            /*HERE I WANT TO CHANGE GRID COLOR*/
        }
    }
}

对不起,我的英语不好.

Sorry for my bad english.

最诚挚的问候.

推荐答案

首先,您应该实施

Fitst of all you should implement INotifyPropertyChanged in your ViewModel:

public class MainWindowViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

然后,将NotifyPropertyChanged()添加到属性设置器中.

Then, add NotifyPropertyChanged() to your properties setter.

好的.接下来,将具有网格背景颜色的新Property添加到ViewModel:

Ok. Next, add new Property with your grid background color to your ViewModel:

private Brush _gridBackground;
public Brush GridBackground
{ 
    get { return _gridBackground; }
    set
    {
        _gridBackground = value;
        NotifyPropertyChanged();
    }
}

并将网格的背景绑定到您的媒体资源:

And bind your grid's background to your property:

<Grid Background="{Binding GridBackground}">

最后,您可以在命令处理程序中更改GridBackground:

Finally you can just change GridBackground in the command handler:

public void ChangeBgColor(object obj)
{
    GridBackground = Brushes.Blue;
}

您应该记住,将类似Brush的WPF类添加到代码中是一种不好的做法.更好的方法是使用 XModel代码中的IValueConverter 和ViewModel中的BCL类.例如,您可以在ViewModel中使用枚举,然后在ValueConverter中将其转换为brush.

You should remember that it's a bad practice to add WPF-classes like Brush to your code. The better way is to use IValueConverter in XAML code and BCL classes in your ViewModel. For example, you can use enumeration in ViewModel and convert it to brush in ValueConverter.

  1. 为ViewModel的属性添加新的枚举:

  1. Add new enum for your ViewModel's property:

public enum GridState { Valid, Invalid }

  • 更改属性类型:

  • Change property type:

    private GridState _gridBackground;
    public GridState GridBackground
    { 
        get { return _gridBackground; }
        set
        {
            _gridBackground = value;
            NotifyPropertyChanged();
        }
    }
    

  • 使用值转换器添加新类

  • Add new class with value converter

    public class GridStateToBackgroundColorConverter : IValueConverter
    {
        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            GridState val = (GridState) value;
            if(val == GridState.Valid)
                return Brushes.Green;
            return Brushes.Red;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    
        #endregion
    }
    

  • 向您的控件添加新的静态资源

  • Add new static resource to your control

     <UserControl.Resources>
         <converters:GridStateToBackgroundColorConverter x:Key="gridStateToBackgroundColorConverter" />
     </UserControl.Resources>
    

  • 更新绑定到您的媒体资源

  • Update binding to your property

    <Grid Background="{Binding GridBackground, Converter={StaticResource gridStateToBackgroundColorConverter}">
    

  • 这篇关于MVVM单击更改网格的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆