I have a ListView bound to a view model which contains an ObservableCollection in a simple example app.
public class ViewModel : INotifyPropertyChanged
{
public ViewModel(){}
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Item> _items;
public ObservableCollection<Item> Items
{
get
{
return this._items;
}
set
{
if (value != this._items)
{
this._items = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Items"));
}
}
}
}
public class Item
{
public string Name;
}
The following function is bound to the SelectionChanged event of the ListView
private void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
model.Items.Add(new Item { Name = "added item" });
model.Items = new ObservableCollection<Item> { new Item { Name = "new item 1" }};
}
When the event fires, this should happen
- new item (“added item”) appended to existing
ObservableCollection ObservableCollectionset to a new collection [single item, “new item 1”]
What actually happens:
ObservableCollectionset to new collection [single item, “new item 1”]- new item (“added item”) appended to end of new collection
Can anyone explain why these are happening in the wrong order?
My guess is that they’re not happening in the wrong (reversed) order but the append is happening twice. Executing
in the SelectionChanged of those same Items is pretty bold. It will trigger a SelectionChanged again, and only because the Selection then remains at none (Index -1) you do not get into an infinite loop.