WPF: PropertyChangedCallback triggered only once

前端 未结 4 548
自闭症患者
自闭症患者 2021-01-02 06:57

I have a user control, which exposes a DependencyProperty called VisibileItems Every time that property gets updated, i need to trigger another event. To achieve that, i ad

4条回答
  •  情歌与酒
    2021-01-02 07:24

    You might be having an issue where the contents of the collection is changing but not the actual instance. in this case you'll want to use an ObservableCollection and do something like this:

    public static readonly DependencyProperty VisibleItemsProperty =
        DependencyProperty.Register(
        "VisibleItems",
        typeof(IList),
        typeof(MyFilterList),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, new PropertyChangedCallback(VisibleItemsChanged)));
    
        private static void VisibleItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var myList = d as MyFilterList;
            if (myList == null) return;
    
            myList.OnVisibleItemsChanged(e.NewValue as IList, e.OldValue as IList);
        }
    
        protected virtual void OnVisibleItemsChanged(IList newValue, IList oldValue)
        {
            var oldCollection = oldValue as INotifyCollectionChanged;
            if (oldCollection != null)
            {
                oldCollection.CollectionChanged -= VisibleItems_CollectionChanged;
            }
            var newCollection = newValue as INotifyCollectionChanged;
            if (newCollection != null)
            {
                newCollection.CollectionChanged += VisibleItems_CollectionChanged;
            }
        }
    

提交回复
热议问题