How to update ItemsSource without ObservableCollection

712 views Asked by At

Running the following code will not remove the item from the list box (as it appears to the user)

        lbxUserSecurityGroups.ItemsSource = _currentUserGroups;
        _currentUserGroups.RemoveAt(0);
        lbxUserSecurityGroups.ItemsSource = _currentUserGroups;

but this will:

        lbxUserSecurityGroups.ItemsSource = _currentUserGroups;
        _currentUserGroups.RemoveAt(0);
        lbxUserSecurityGroups.ItemsSource = null;
        lbxUserSecurityGroups.ItemsSource = _currentUserGroups;

My guess is that since I am using the same object for the ItemsSource, that the listbox just doesn't update because it believes it has no reason to (e.g. only updates the item source when it has changed)

Is there some way to force the ItemsSource to update, e.g.:

        lbxUserSecurityGroups.UpdateItemsSource();

Note: I am aware a proper way to do do this would be using an ObservableCollection. But this strikes me as odd behavior and I would expect to be able to do what I am trying without hacking around by setting the value to null before setting it to the proper value.

2

There are 2 answers

0
Matt Burland On

Yes - it won't update because ItemsSource is still a reference to the same object. Setting it to null first will do it (as you saw). Or you can use an ObservableCollection or you can use your own collection that implements the appropriate interface INotifyCollectionChanged.

The binding is smart enough not to update when you try and set a property to the same reference that it already has. If it didn't, you'd end up with a lot of redundant updates and all your properties would need to handle checking if the new value is the same as the current which would be tedious.

0
Steve On

You can use something like the following to force a refresh. This might incur less overhead than the way you're currently doing it (events have to be unsubscribed/resubscribed, and a new Binding object might have to get created - although I'm not 100% sure about what's going on behind the scenes).

lbxUserSecurityGroups.GetBindingExpression(ItemsSourceProperty).UpdateTarget();