DependencyProperty getter / setter没有被调用

我试图创建派生自标准网格的自定义控件。我添加了一个ObservableCollection作为Custom控件的DependencyProperty。但是,永远不会达到它的获取/设置。在创建可以与ObservableCollection一起正常工作的DependencyProperty时,我可以有一些指导吗?


public class MyGrid : Grid

{

    public ObservableCollection<string> Items

    {

        get

        {

            return (ObservableCollection<string>)GetValue(ItemsProperty);

        }

        set

        {

            SetValue(ItemsProperty, value);

        }

    }


public static  DependencyProperty ItemsProperty =

                DependencyProperty.Register("Items", typeof(ObservableCollection<string>), 

        typeof(MyGrid), new UIPropertyMetadata(null, OnItemsChanged));


}


拉莫斯之舞
浏览 653回答 2
2回答

红颜莎娜

我建议不要将ObservableCollection用作Items依赖项属性的类型。在这里拥有ObservableCollection的原因(我想)是为了在CollectionChanged分配属性值时使UserControl能够附加处理程序。但是ObservableCollection太具体了。WPF中的方法(例如在ItemsControl.ItemsSource中)是定义一个非常基本的接口类型(如IEnumerable),并在为属性分配值时,找出值集合是否实现了某些更特定的接口。这里至少是INotifyCollectionChanged,但是该集合也可以实现ICollectionView和INotifyPropertyChanged。所有这些接口不是强制性的,这将使您的依赖项属性可以绑定到各种类型的集合,从普通数组开始直到复杂的ItemCollection。OnItemsChanged然后,您的属性更改回调将如下所示:private static void OnItemsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e){&nbsp; &nbsp; MyGrid grid = obj as MyGrid;&nbsp; &nbsp; if (grid != null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var oldCollectionChanged = e.OldValue as INotifyCollectionChanged;&nbsp; &nbsp; &nbsp; &nbsp; var newCollectionChanged = e.NewValue as INotifyCollectionChanged;&nbsp; &nbsp; &nbsp; &nbsp; if (oldCollectionChanged != null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; oldCollectionChanged.CollectionChanged -= grid.OnItemsCollectionChanged;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (newCollectionChanged != null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newCollectionChanged.CollectionChanged += grid.OnItemsCollectionChanged;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // in addition to adding a CollectionChanged handler&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // any already existing collection elements should be processed here&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}private void OnItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e){&nbsp; &nbsp; // handle collection changes here}
打开App,查看更多内容
随时随地看视频慕课网APP