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;
}
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With