mvvm - PropertyChanged not updating GUI with list modification, but does if I assign a new list - C# silverlight
My ViewModel contains a List<string> SelectedActions
and a method AddSelectedAction(string addMe)
SelectedActions.Add(addMe);
OnPropertyChanged("SelectedActions"开发者_如何学C);
But if I use this then it works:
SelectedActions.Add(addMe);
List<string> li = new List<string>();
foreach (string st in SelectedActions)
li.Add(st);
SelectedActions = li;
OnPropertyChanged("SelectedActions");
Where I have the following utility function
protected void OnPropertyChanged(string propertyName)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
As well as implementing INotifyPropertyChanged
OnPropertyChanged
call, so I know it's at least doing somethingI would recommend changing your List<string>
to ObservableCollection<string>
. It's the standard/recommended way of storing collections that need to notify when they have been updated/changed.
This will handle all of the change notification for you and you won't need to explicitly call OnPropertyChange()
That is because the object that has been given SelectedActions
is doing a minor optimization. You told it the property has changed, but it did a quick call to Equals() and found it's still the same object, so it short circuited updating the value. When you assign a new list to SelectedActions, then the control sees it's an entirely new object and therefore does the update.
The easiest fix is to use an ObservableCollection
, which implements INotifyCollectionChanged
, which is the interface designed to handle this situation.
I would guess that what you want here is an ObservableCollection, rather than a List. I'm not sure what kind of UI you're expecting to see updated, but adding an object to a list doesn't change the list itself, so the UI wouldn't see that there's anything to update.
Th reason that your second piece of code works is that, by assigning the variable to a completely new list, the databinding engine sees all of the values as new and binds them accordingly.
If there are other things that need to be done on the adding or removing of items from your collection, ObservableCollection supports a CollectionChanged event that gets fired whenever an object is added or removed from the list. By default, this event also fires the NotifyPropertyChanged event to update your UI, so you don't need to add this manually.
You need an ObservableCollection<T>
for what you're trying to accomplish. A list does not raise any events when items are added or removes, so the UI has no way to know it needs to be updated.
精彩评论