tags:

views:

1653

answers:

2

In a view model, I have a collection of items of type "ClassA" called "MyCollection". ClassA has a property named "IsEnabled".

class MyViewModel 
{
    List<ClassA> MyCollection { get; set; }

    class ClassA { public bool IsEnabled { get; set; } }
}

My view has a datagrid which binds to MyCollection. Each row has a button whose "IsEnabled" attribute is bound to the IsEnabled property of ClassA.

When conditions in the view model change such that one particular item in the MyCollction list needs to bow be disabled, I set the IsEnabled property to false:

MyCollection[2].IsEnabled = false;

I now want to notify the View of this change with a OnPropertyChanged event, but I don't know how to reference a particular item in the collection.

OnPropertyChanged("MyCollection");
OnPropertyChanged("MyCollection[2].IsEnabled");

both do not work.

How do I notify the View of this change? Thanks!

+3  A: 

Instead of using a List, try using an ObservableCollection. Also, modify your ClassA so that it implements INotifyPropertyChanged, particularly for the IsEnabled property. Finally, modify your MyViewModel class so it also implements INotifyPropertyChanged, especially for the MyCollection property.

Scott Whitlock
+5  A: 

ClassA needs to implement INotifyPropertyChanged :

class ClassA : INotifyPropertyChanged
{
    private bool _isEnabled;
    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            if (value != _isEnabled)
            {
                _isEnabled = value;
                OnPropertyChanged("IsEnabled");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

EDIT: and use an ObservableCollection like Scott said

Thomas Levesque
The ObservableCollection is not required - implementing INotifyPropertyChanged was sufficient. Thanks!
Adam Barney
Well, it is sufficient to be notified when IsEnabled is changed, but if items are added to or removed from MyCollection, you won't be notified unless it is an ObservableCollection (or any class that implements INotifyCollectionChanged)
Thomas Levesque