Previously, I explained how to extend the ExtendedFlexLayout class so that it can bind to collections that change at runtime, with the changes being reflected on screen. While the ExtendedFlexLayout class only handles items being added to and removed from the bound collection at runtime, I mentioned that it could easily be extended to handle additional actions by examining the Action property.
In this blog post, I’ll examine how to extend the ExtendedFlexLayout class so that it can respond to the bound collection being cleared at runtime. The sample this code comes from can be found on GitHub.
Clearing the Collection
The ExtendedFlexLayout can respond to the bound collection being cleared at runtime in the handler for the CollectionChanged event:
void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { // Items cleared Children.Clear(); } if (e.OldItems != null) { // Items removed Children.RemoveAt(e.OldStartingIndex); } if (e.NewItems != null) { // Item(s) added. for (int i = 0; i < e.NewItems.Count; i++) { var item = e.NewItems[i]; var view = CreateChildView(item); Children.Insert(e.NewStartingIndex + i, view); } } }
At the top of the event handler, the received NotifyCollectionChangedEventArgs are used to determine whether to clear the ExtendedFlexLayout control. The event argument data includes an Action property, which identifies whether an item has been added, moved, removed, replaced, or whether the collection has been cleared. If the bound collection has been cleared, the Action property will be set to NotifyCollectionChangedAction.Reset and the control responds by clearing the Children collection. When the Children collection has been cleared, both the OldItems (the list of items that have been replaced, removed, or moved within the collection) and NewItems (the list of items that have been added to the collection) properties will be null, so the code for adding and removing items won’t be executed on this invocation of the event handler.
Summary
This blog post has explained how to further extend the ExtendedFlexLayout class so that it can respond to the bound collection being cleared at runtime. This is achieved by clearing the Children collection of the control when the Action property of the handler that responds to the CollectionChanged event is equal to NotifyCollectionChangedAction.Reset.
The sample this code comes from can be found on GitHub.
No comments:
Post a Comment