How do you handle data grid cell changes with MVVM?

前端 未结 2 1984
[愿得一人]
[愿得一人] 2021-01-13 01:45

I\'m trying to figure out how to handle changes in a data grid cell while keeping within the MVVM design pattern. When the user changes the value in a cell, I have to go off

相关标签:
2条回答
  • 2021-01-13 02:10

    Usually i do this with interaction triggers from Galasoft.

     <DataGrid IsReadOnly="False">
                <e:Interaction.Triggers>
                    <e:EventTrigger EventName="CellEditEnding">
                        <GalaSoft_MvvmLight_Command:EventToCommand PassEventArgsToCommand="True" Command="{Binding CellEditEndingCommand}"/>
                    </e:EventTrigger>
                </e:Interaction.Triggers>
            <DataGrid.Columns>
                   ...                        
        </DataGrid.Columns>
    </DataGrid>
    

    Then inside ViewModel you create generic RelayCommand where generic type is type of corresponding EventArgs.

    RelayCommand<DataGridCellEditEndingEventArgs> CellEditEndingCommand {get; set;}
    

    Initialization:

    CellEditEndingCommand = new RelayCommand<DataGridCellEditEndingEventArgs>(args=>DoSomething());
    
    0 讨论(0)
  • 2021-01-13 02:12

    Let's assume your DataGrid'sItemsSource is bound, TwoWay-mode, to something in your ViewModel, let's call it CustomObject or whatever.

    Let's assume then that a specific DataGridCell is bound to a Property named SomeProperty, which is declared as follows:

    private string someProperty;
    public string SomeProperty {
      get { return someProperty; }
      set {
        someProperty = value;
        //Fire OnPropertyChanged here
      }
    }
    

    Put a breakpoint just on the set. Then, modify the cell in your View : the breakpoint will be reached.

    This allows you to simulate an event: each time the set is called, it means the cell is gonna change, do whatever you want now with the changing process (you can for example test the new value, by testing on value, or keep the last value, by saving someProperty somewhere before the line someProperty = value; )

    0 讨论(0)
提交回复
热议问题