繁体   English   中英

MVVM在点击时更改网格的背景颜色

[英]MVVM changing grid's background color on click

我是MVVM模式的真正初学者。 我正试图在按钮的点击上更改网格的背景。 我有一个包含按钮的网格的xaml,以及一个ViewModel .cs,我希望在按钮的单击时更改网格的背景。 直到我点击时才能成功显示MessageBox ...

.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代码:

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*/
        }
    }
}

对不起,我的英语不好。

最好的祝福。

最适合你应该在ViewModel中实现INotifyPropertyChanged

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()添加到属性设置器。

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

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

并将您的网格背景绑定到您的财产:

<Grid Background="{Binding GridBackground}">

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

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

您应该记住,将诸如Brush之类的WPF类添加到代码中是一种不好的做法。 更好的方法是在XAML代码中使用IValueConverter ,在ViewModel中使用BCL类。 例如,您可以在ViewModel中使用枚举并将其转换为ValueConverter中的画笔。

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

     public enum GridState { Valid, Invalid } 
  2. 更改属性类型:

     private GridState _gridBackground; public GridState GridBackground { get { return _gridBackground; } set { _gridBackground = value; NotifyPropertyChanged(); } } 
  3. 添加带有值转换器的新类

     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 } 
  4. 向控件添加新的静态资源

      <UserControl.Resources> <converters:GridStateToBackgroundColorConverter x:Key="gridStateToBackgroundColorConverter" /> </UserControl.Resources> 
  5. 更新绑定到您的属性

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

如果要更改网格背景颜色,则可以使用命令参数。 您可以将任何UI控件作为Command参数传递。 在您的情况下,传递网格以访问视图模型中的网格。 将名称赋给网格并使用该名称作为命令参数。 为此,您需要实现如下代码:

<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 Name="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}"
        CommandParameter="{Binding Elementname="grid"}"/>
</Grid>

对.xaml文件进行此更改后。 实现参数化中继命令以使用此传递的Grid在Viewmodel文件中使用。 实现参数化中继命令尝试实现以下代码:

    private ICommand m_ButtonCommand;
    public ICommand ButtonCommand
    {
        get
        {
            return m_ButtonCommand;
        }
        set
        {
            m_ButtonCommand = value;
        }
    }

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

    public void ChangeBgColor(Grid grid)
    {
        if(grid!=null)
            grid.Background = Brushes.Red; //Any color you want to change.
    }

我希望这会奏效。 谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM