Wpf MVVM ObservableCollection <string> does not refresh view

I am having a problem when my ObservableCollection is not updating the view. I can place a breakpoint before OnPropertyChange and verify that my collection has names in them.

In my model, I have an event that fires a list with random names in it.

in my model model I subscribe to this event and my event handler does this

void _manager_ProcessesChanged(List<string> n) { //create a new collection to hold current Ids ObservableCollection<string> names = new ObservableCollection<string>(); //copy ids into our collection foreach (string name in n) { names.Add(name); } Names = names; } 

The myNames property looks like this

 ObservableCollection<string> _names = new ObservableCollection<string>(); public ObservableCollection<string> Names { get { return _names; } set { _names = value; OnPropertyChanged("Names"); } } 

and the binding of my view is as follows

 <Window.DataContext> <vm:MainWindowViewModel/> </Window.DataContext> <Grid> <ListBox ItemsSource="{Binding Path=Names}"/> </Grid> 

If I changed the collection from <string> to <int> , it works fine ... what am I missing?

+4
source share
2 answers

I also came across this. Not sure if this is the perfect solution (certainly not like this), but it worked for me.

 void _manager_ProcessesChanged(List<string> n) { Names.Clear(); //copy ids into our collection foreach (string name in n) { Names.Add(name); } } 
+2
source

If you re-create the ObservableCollection, you will lose the binding to the collection.

You must have .Clear (...) and .Add (...) elements, and you should also just change the ObservableCollection Names to an auto-property. No need to call OnPropertyChanged here, as it is handled by the type for you.

+5
source

All Articles