1

I have a datagrid that I would like to, whenever values in any cell change in gui, updates other properties in the view model.

I have seen this but I wonder if could be done by binding an event such as SourceUpdated or CurrentCellChanged, like the following:

(view)

<DataGrid ItemsSource="{Binding Terrain, Mode=TwoWay, NotifyOnSourceUpdated=True}" 
          Grid.Column="0" Grid.Row="15" Grid.ColumnSpan="1" 
          AutoGenerateColumns="True"
          CanUserAddRows="True" 
          CanUserDeleteRows="True"
          SourceUpdated="{Binding TerrainChangedEvent }" Margin="0,6,0,20" Grid.RowSpan="2"/>

and and in view model

public EventHandler<EventArgs> TerrainChangedEvent;
public ObservableCollection<TerrainSpec> Terrain
{
    get { return _terrain; }
    set { _terrain = value; ReCalcOtherProperty();  RaisePropertyChanged(nameof(Terrain));
}

public TerrainViewModel()
{
    Terrain = new ObservableCollection<TerrainSpec>()
    TerrainChangedEvent += RaiseTerrainChanged;
}
private void RaiseTerrainChanged(object sender, EventArgs e)
{
    ReCalcOtherProperty();
    RaisePropertyChanged(nameof(Terrain));
}

and model

public class TerrainSpec : INotifyPropertyChanged
{
    private double _height;
    private double _distance;

    public double Distance
    {
        get { return _distance; }
        set { _distance = value; RaisePropertyChanged(nameof(Distance)); }
    }
    public double Height
    {
        get { return _height; }
        set { _height = value; RaisePropertyChanged(nameof(Height)); }
    }

    public override string ToString()
    {
        return $"{Distance:F2} m, {Height:F2} m";
    }

    #region PropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}

However this throws an error when I try to start it:

InvalidCastException: Unable to cast object of type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'

Is there a way to do this?

kara
  • 3,205
  • 4
  • 20
  • 34
Erik Thysell
  • 1,160
  • 1
  • 14
  • 31

0 Answers0