Search code examples
wpfwpf-controlswpfdatagridobservablecollection

What event is fired when I change an element on the observable collection?


I have a data grid in my view that binds to an observable collection in my view model.

When I do this:

myObservableCollection[2] = myItem;

The data grid refresh the items, and for example, if I have shorted the elements in the data grid, if myItem has updated a field that is affected by the short, is put in its new position.

However, I would like to scroll to the new position, so I am trying to use an attached behavior, that is works good when the event selection changed is fired, but I need to know what event is fired when I reasign myItem.

I have try to catch the events AddingNewItem and SourceUpdated, but neither of them is fired.


Solution

  • Netaholic gave a good part of the answer, but just to complete and put some clear visible code :

    public void Demo()
    {
        ObservableCollection<String> collec = new ObservableCollection<String>() {"hello"};
        collec.CollectionChanged += CollectionChanged;
        collec[0] = "goodbye";
    }
    void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                break;
            case NotifyCollectionChangedAction.Move:
                break;
            case NotifyCollectionChangedAction.Remove:
                break;
            case NotifyCollectionChangedAction.Replace:
                Debug.WriteLine("The event you re expecting");
                break;
            case NotifyCollectionChangedAction.Reset:
                break;
            default:
                break;
        }
    }
    

    In the second parameter, you 'll find the index and object that is replaced

    Regards