Home > Back-end >  How to handle the event when I modify value in the item of a datagrid?
How to handle the event when I modify value in the item of a datagrid?

Time:11-11

I have a datagrid. One column is a checkbox and I would like to handle when the checkbox of a row is modified.

I have seen this code, that at first it looks what I am looking for, but I have some doubts.

public ObservableCollection<YourDataType> Items
{
    get { return items; }
    set { items = value; NotifyPropertyChanged("Items"); }
}

public YourDataType SelectedItem
{
    get { return selectedItem; }
    set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}

In the view model constructor:

SelectedItem.PropertyChanged  = SelectedItem_PropertyChanged;

In the view model:

private void SelectedItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    // this will be called when any property value of the SelectedItem object changes
    if (e.PropertyName == "YourPropertyName") DoSomethingHere();
    else if (e.PropertyName == "OtherPropertyName") DoSomethingElse();
}

My doubt is that in the constructor it is subscribe to the event of the selected item, but the selected item is changed when I select another row in the datagrid. So is it subscribe only once? To which item?

Also, the selected item is null at constructor time, so I guess I will get an null error, I guess.

So I really I am not sure if this really a good solution, and if it is, I don't understand why it can work.

There is another solution to can handle when a property of one of the items in the datagrid is changed? But at first, this solution seems clear and simple.

The solution is from here.

Thanks.

CodePudding user response:

You would have to attach and detach the event handler in the SelectedItem property setter:

public YourDataType SelectedItem
{
    get { return selectedItem; }
    set
    { 
        if (selectedItem != null)
        {
            selectedItem.PropertyChanged -= SelectedItem_PropertyChanged;
        }
        selectedItem = value;
        if (selectedItem != null)
        {
            selectedItem.PropertyChanged  = SelectedItem_PropertyChanged;
        }
        NotifyPropertyChanged(nameof(SelectedItem));
    }
}
  • Related