private static void OnComparerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CollectionSortBehavior behavior = (CollectionSortBehavior)d;

            SortComparer oldComparer = (SortComparer)e.OldValue;

            behavior.UnregisterComparer(oldComparer);

            SortComparer newComparer = (SortComparer)e.NewValue;

            behavior.RegisterComparer(newComparer);

            behavior.SortItems();
        }
        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CollectionSortBehavior behavior = (CollectionSortBehavior)d;

            IEnumerable oldSource = (IEnumerable)e.OldValue;

            behavior.UnregisterItemsSource(oldSource);

            IEnumerable newSource = (IEnumerable)e.NewValue;

            behavior.RegisterItemsSource(newSource);

            SortComparer comparer = behavior.Comparer;

            if (comparer != null)
            {
                comparer.ItemsSource = newSource;
            }

            behavior.SortItems();
        }
        private void OnItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
            case NotifyCollectionChangedAction.Add:
            {
                AddSortedItem(Comparer, SortedItems, e.NewItems[0]);
                break;
            }

            case NotifyCollectionChangedAction.Remove:
            {
                RemSortedItem(Comparer, SortedItems, e.OldItems[0]);
                break;
            }

            case NotifyCollectionChangedAction.Replace:
            {
                SortComparer     comparer = Comparer;
                SortedCollection sorted   = SortedItems;
                RemSortedItem(comparer, sorted, e.OldItems[0]);
                AddSortedItem(comparer, sorted, e.NewItems[0]);
                break;
            }

            case NotifyCollectionChangedAction.Move:
            {
                // nothing to do
                break;
            }

            case NotifyCollectionChangedAction.Reset:
            {
                SortItems();
                break;
            }
            }
        }