Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created July 7, 2023 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emoacht/d7c2dcda5b5b170e40729183004cf936 to your computer and use it in GitHub Desktop.
Save emoacht/d7c2dcda5b5b170e40729183004cf936 to your computer and use it in GitHub Desktop.
Behavior to capture the change of source collection.
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