Custom ItemsSource property for a UserControl

user1184598 picture user1184598 · Feb 27, 2012 · Viewed 17k times · Source

Does anyone know how to make a custom ItemsSource?

What I want to do is to make an itemsSource to my own UserControl so that it could be bound by ObservableCollection<>.

Also, I could know Whenever the number of items in the itemsSource updated, so as to do further procedures.

Thank you so much.

Answer

gaurawerma picture gaurawerma · Feb 27, 2012

You may need to do something like this in your control

public IEnumerable ItemsSource
{
    get { return (IEnumerable)GetValue(ItemsSourceProperty); }
    set { SetValue(ItemsSourceProperty, value); }
}

public static readonly DependencyProperty ItemsSourceProperty =
    DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(UserControl1), new PropertyMetadata(new PropertyChangedCallback(OnItemsSourcePropertyChanged)));

private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    var control = sender as UserControl1;
    if (control != null)
        control.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
}



private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
    // Remove handler for oldValue.CollectionChanged
    var oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;

    if (null != oldValueINotifyCollectionChanged)
    {
        oldValueINotifyCollectionChanged.CollectionChanged -= new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
    }
    // Add handler for newValue.CollectionChanged (if possible)
    var newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;
    if (null != newValueINotifyCollectionChanged)
    {
        newValueINotifyCollectionChanged.CollectionChanged += new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
    }

}

void newValueINotifyCollectionChanged_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    //Do your stuff here.
}