Update Listbox.ItemsSource when not using ObservableCollection

When you’re using an ObservableCollection<T> which implements the INotifyPropertyChanged interface, updating the source of items for a ListBox or other control can be done almost “automatically” with DataBinding.  But, if you’re using a basic List<T> as an ItemSource for say a ListBox, then any changes to the List<T> aka the “ItemSource,” will not be immediately reflected in the ListBox control.

A simple way to address this, so the ListBox reflects any changes to the List<T>, is to assign your ListBox.ItemSource  a null value.  Then reassign the ListBox.ItemSource to the List<T>.

 

ListBoxItemSource

2 thoughts on “Update Listbox.ItemsSource when not using ObservableCollection

  1. Thanks for the solution, seems to work when I tested it. However it doesn’t work when I have something like this on a button-click event:

    lbxTraits.ItemsSource = null;
    lbxTraits.ItemsSource = “{Binding TraitsList}”;

    My Listbox simply goes blank and nothing updates. The Listbox does get populated if I set the ItemsSource initially in the xaml and load the page, but it gets cleared when I set it in the behind-code for the button-click. Any ideas? Thanks again!

    1. If you’re using Databinding, implement the INotifyPropertyChangedInterface on your collection. This is generally considered the best approach.

      Or, in your above example, try this in the .cs file for the button_click event:

      lbxTraits.ItemsSource = null;
      lbxTraits.ItemsSource = TraitsList;

      Sorry the for late reply.

      Chris

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s