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