tags:

views:

101

answers:

3

I have a WPF Toolkit DataGrid bound to an ObservableCollection of Car in my view model. Car has a PropertyChanged event and the setters of each of its two string properties fire the event. I also have the grid's SelectedItem property bound to a property in the view model of type Car, also called SelectedItem.

On the same window as the grid, I have buttons for add, modify and delete. Add and modify open a dialog window with two textboxes, one for each Car property. Delete just shows a confirm dialog then does the delete.

For add and delete, I add or delete an item from the ObservableCollection and the grid updates itself as expected. However, for modify it does not. At first, my Car did not use PropertyChanged and after some searching I found that it needed to for the grid to update when an individual item's properties changed. But now that I am using PropertyChanged, the grid still doesn't update.

I've tried changing the values of the SelectedItem in my view model as well as directly changing the item on the collection.

What am I doing wrong?

A: 

What does the DataGrid's binding look like? Can you provide some code?

Matthew Cole
A: 

Sounds like the classic problem with ObservableCollection. ObservableCollection only notifies of additions, deletions, etc. on it's self. It will NOT notify of changes to properties of whatever you have stored in it. This is why your add/delete operations work as expected.

What you should do is use a CollectionView and bind to that:

ObservableCollection<MyObject> myCollection = new ObservableCollection<MyObject>();    
ICollectionView view = CollectionViewSource.GetDefaultView(myCollection);

using this method also has the benifit that grouping and sorting are built into the view.

Muad'Dib
+1  A: 

Make sure you're implementing INotifyPropertyChanged and not just raising a PropertyChanged event. Also, when raising PropertyChanged, you must pass "this" as the sender, otherwise WPF will ignore the event.

Below is a simple base class that implements INotifyPropertyChanged.

public class Person : INotifyPropertyChanged {

    private string name;

    public string Name {
        get { return name; }
        set { 
            if (name != value) {
                name = value;
                OnPropertyChanged("Name");
            }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName) {
        var handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}
Josh Einstein
Thank you Josh - I was raising the event but not implementing the interface. Duh :)
MarkB