UserControl的Custom ItemsSource属性 [英] Custom ItemsSource property for a UserControl

查看:142
本文介绍了UserControl的Custom ItemsSource属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道如何自定义 ItemsSource

Does anyone know how to make a custom ItemsSource?

我想做的是做一个 itemsSource 到我自己的 UserControl ,以便它可以被 ObservableCollection<> code>。

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

另外,我可以知道每当 itemsSource 中的项目数量更新,那么作为进一步的程序。

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

非常感谢你。

推荐答案

您可能需要在控件中执行此操作

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.
}

这篇关于UserControl的Custom ItemsSource属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆