collection dependency properties

后端 未结 2 1256
余生分开走
余生分开走 2020-12-03 16:03

I have a custom control that has a DependencyProperty of type ObservableCollection that is bound to an observableCollection:



        
2条回答
  •  青春惊慌失措
    2020-12-03 16:54

    In addition to what grantz has answered, I would suggest to declare the property with type IEnumerable and check at runtime if the collection object implements the INotifyCollectionChanged interface. This provides greater flexibility as to which concrete collection implementation may be used as property value. A user may then decide to have their own specialized implementation of an observable collection.

    Note also that in the ColumnsPropertyChanged callback the CollectionChanged event handler is attached to the new collection, but also removed from the old one.

    public static readonly DependencyProperty ColumnsProperty =
        DependencyProperty.Register(
            "Columns", typeof(IEnumerable), typeof(MyControl),
            new PropertyMetadata(null, ColumnsPropertyChanged));
    
    public IEnumerable Columns
    {
        get { return (IEnumerable)GetValue(ColumnsProperty); }
        set { SetValue(ColumnsProperty, value); }
    }
    
    private static void ColumnsPropertyChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var control= (MyControl)obj;
        var oldCollection = e.OldValue as INotifyCollectionChanged;
        var newCollection = e.NewValue as INotifyCollectionChanged;
    
        if (oldCollection != null)
        {
            oldCollection.CollectionChanged -= control.ColumnsCollectionChanged;
        }
    
        if (newCollection != null)
        {
            newCollection.CollectionChanged += control.ColumnsCollectionChanged;
        }
    
        control.UpdateColumns();
    }
    
    private void ColumnsCollectionChanged(
        object sender, NotifyCollectionChangedEventArgs e)
    {
        // optionally take e.Action into account
        UpdateColumns();
    }
    
    private void UpdateColumns()
    {
        ...
    }
    

提交回复
热议问题