AsyncObservableCollection - Aghyad-Khlefawi/Coddee GitHub Wiki
This collection is a simple implementation of a ObservableCollection that is thread safe, this collection is very useful in WPF applications or in any application that requires a single thread to interact with the collection. For example in a WPF application if you bind a collection to a list of any UI element then only the UI thread must add or edit the list.
| Name | Description |
|---|---|
| Fill | Copy the content of another collection |
| FillAsync | Insert the result of a Task to the collection |
| Name | Description |
|---|---|
| IsBusy | This property will be set to true when the FillAsync method is executing and false when is completed (Useful to bind to a busy indicator) |
| SelectedItem | Holds a reference to the selected item in the collection (Can be bound to SelectedItem property of a list or grid) |
| Name | Description |
|---|---|
| SelectedItemChanged | Triggered when the setter on the SelectedItem Property is called |
The best way to create an instance of this collection is to use the factory method AsyncObservableCollection.Create() which will create the collection on the UI thread.
C# Example:
//Set the owning thread in start of the application
UISynchronizationContext.SetContext(SynchronizationContext.Current);
//Create the collection
var collection = AsyncObservableCollection<Person>.Create();
//Subscribe to the SelectedItemChanged event
collection.SelectedItemChanged += (sender, item) =>
{
MessageBox.Show($"An item was selected {item.FirstName}");
};
var person = new Person{FirstName = "Aghyad"};
//Add an item to the collection
collection.Add(person);
//Set the selected item (This will trigger the SelectedItemChanged event)
collection.SelectedItem = person;
//Add more items to the collection in this case using a method (GetFromDatabase) which returns Task<IEnumerable<Person>>
await collection.FillAsync(GetFromDatabase());