-2

On startup i bind an ObservableCollection to a menu:

Menu.ItemsSource = _manager.Selection;

This menu correctly displays all objects from the collection.

Now i want to update the collection and add/remove some of the items in it:

private void OnBoxClick(object sender, RoutedEventArgs e)
    {
        _manager.Selection = _manager.GetNewSelection();
        PropertyChanged?.Invoke(this, new CollectionChangeEventArgs(CollectionChangeAction.Refresh, _manager.Selection));
    }

    public event CollectionChangeEventHandler PropertyChanged;

But the ui is still displaying how it was before..

What is missing?

Loading
  • 1,098
  • 1
  • 12
  • 25
  • Why is it an ObservableCollection at all, when you seemingly never add or remove elements? Use an ordinary `public List Selections` property that fires the PropertyChanged event of the INotifyPropertyChanged interface when it is set. – Clemens Oct 11 '18 at 13:54

1 Answers1

1

You should either re-set the Menu.ItemsSource property (to _manager.GetNewSelection()) or add or remove items from _manager.Selection. Setting the _manager.Selection field to another instance of an ObservableCollection<T> won't affect the menu's ItemsSource property.

If you get a completely new collection from the _manager.GetNewSelection(), you might as well just do this:

private void OnBoxClick(object sender, RoutedEventArgs e)
{
    Menu.ItemsSource = _manager.GetNewSelection();
}

And then it doesn't matter whether _manager.GetNewSelection returns an ObservableCollection or any other kind of IEnumerable that doesn't provide notifications when items are added or removed.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • or use `Binding` to ding menu's `itemsSource` to manager's `Selection` property – Taras Shcherban Oct 11 '18 at 13:54
  • Yes, but since OnBoxClick apparently is an event handler in the view, there is no real point of binding here. – mm8 Oct 11 '18 at 14:03
  • so right now i cleared the selection, and then added the "new" objects. After that i fired the propertychanged event but it still doesnt refresh the menu. I also tried to set itemssource = _manager.GetNetSelection() but it still doesnt refresh the ui – Loading Oct 11 '18 at 14:04
  • @Loading: Then you are touching the wrong instance or the collection hasn't changed. – mm8 Oct 11 '18 at 14:06
  • the problem was that i cant use this code in a menu "onclick" function. I had to use mouseenter to trigger the "update" – Loading Oct 11 '18 at 14:18
  • @Loading: This has nothing to do with your original question. If your issue has been solved, please remember to accept the answer to close it. – mm8 Oct 11 '18 at 14:19