Does a property within an ObservableCollection require a PropertyChangedEvent
Do properties on an object within an Observable collection require a PropertyChangedEvent? For example:
public class MyObject
{
public int MyProperty { get; set;}
}
public class MyViewModel
{
ObservableCollection<MyObject> MyObjects = new ObservableCollection<MyObject>();
}
From what I can tell, if I execute MyObjects[0].MyProperty = 1;
then my binding doesn't occur. Howe开发者_Python百科ver, if I call MyObjects.Add(new MyObject());
the binding does occur.
In the first line, MyProperty exists on the first object in the collection MyObjects and not on the collection itself. So the MyObject class would need to implement INotifyPropertyChanged if you expect WPF to listen to changes of that property of the MyObject instance.
You need to implement in your object INotifyPropertyChanged
, because the ObservableCollection
only notifies about collection-changes but not about object changes.
If you are working with WPF, you can derive your MyObject
from DependencyObject. With that done, you can declare your properties as DependencyProperties (VisulStudio has a nice Snippet for that), this does notifying automatically. If you're creating ViewModels, this is makes sense anyway.
精彩评论