Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to refresh ListBox with custom ItemsSource?

I'm using ListBox with custom ItemsSource:

this.ListOfPersonsListBox.ItemsSource = (List<Person>)ListOfPersons.AllPersons;

ListOfPersons is a static class so it cannot implement INotifyPropertyChanged nor IObservableCollection.

What's the simplest way to redraw my ListBox after updating the list? My current code works, but I would like to find a cleaner solution:

    private void SyncButton_Click(object sender, EventArgs e)
    {
        ListOfPersons.Sync();
        this.ListOfPersonsListBox.ItemsSource = null;
        this.ListOfPersonsListBox.ItemsSource = ListOfPersons.AllPersons;
    }
like image 986
Shaeak Silentread Avatar asked Jun 07 '11 15:06

Shaeak Silentread


2 Answers

Consider using an ObservableCollection instead of a List. It implements INotifyPropertyChanged internally. You can loop through your list and add each element to a new ObservableCollection object and bind this to the ListBox.

If you're going to convert often, you could just create an Extension method

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> myList)
{
    var oc = new ObservableCollection<T>();
    foreach (var item in myList)
        oc.Add(item);
    return oc;
}
like image 194
keyboardP Avatar answered Oct 12 '22 15:10

keyboardP


Shaeak,

The Application class lives for the duration of the app lifecycle. If you have something that needs to be accessible from multiple pages throughout the app's life, one solution is to create a partial class that inherits from Application and create a property on this partial class.

This article has an explanation about two thirds of the way down the page.

like image 23
Josh Earl Avatar answered Oct 12 '22 15:10

Josh Earl