Created
July 7, 2023 00:01
-
-
Save emoacht/d7c2dcda5b5b170e40729183004cf936 to your computer and use it in GitHub Desktop.
Behavior to capture the change of source collection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Specialized; | |
using System.ComponentModel; | |
using System.Windows.Controls; | |
using System.Windows.Controls.Primitives; | |
using Microsoft.Xaml.Behaviors; | |
public class ItemsControlBehavior : Behavior<ItemsControl> | |
{ | |
protected override void OnAttached() | |
{ | |
base.OnAttached(); | |
var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(ItemsControl)); | |
dpd?.AddValueChanged(AssociatedObject, OnItemsSourceChanged); | |
AddSourceCollection(); | |
} | |
protected override void OnDetaching() | |
{ | |
base.OnDetaching(); | |
var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(ItemsControl)); | |
dpd?.RemoveValueChanged(AssociatedObject, OnItemsSourceChanged); | |
RemoveSourceCollection(); | |
} | |
private void OnItemsSourceChanged(object? sender, EventArgs e) | |
{ | |
RemoveSourceCollection(); | |
AddSourceCollection(); | |
} | |
private INotifyCollectionChanged? _collection; | |
private void AddSourceCollection() | |
{ | |
_collection = AssociatedObject.ItemsSource as INotifyCollectionChanged; | |
if (_collection is not null) | |
{ | |
_collection.CollectionChanged += OnItemsSourceCollectionChanged; | |
} | |
Apply(); | |
} | |
private void RemoveSourceCollection() | |
{ | |
if (_collection is not null) | |
{ | |
_collection.CollectionChanged -= OnItemsSourceCollectionChanged; | |
} | |
_collection = null; | |
} | |
private void OnItemsSourceCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) | |
{ | |
Apply(); | |
} | |
private void Apply() | |
{ | |
AssociatedObject.IsEnabled = _collection is ICollection { Count: > 1 }; | |
if (AssociatedObject is Selector selector) | |
{ | |
selector.SelectedIndex = 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment