依赖项属性对象未更新到 UI

本文关键字:更新 UI 对象 属性 依赖 | 更新日期: 2023-09-27 18:36:20

我正在努力解决控件中的依赖属性。我的依赖项属性是一个看起来像这样的对象:

public class ChartGroupCollection : ObservableCollection<ChartGroup>, INotifyCollectionChanged
{
    public void ClearDirty()
    {
        foreach (var grp in base.Items)
        {
            foreach(var run in grp.ChartRuns.Where(x=>x.IsDirty))
            {
                run.IsDirty = false;
            }
            grp.IsDirty = false;
        }
    }
    [XmlIgnore]
    public bool IsDirty  //dirty flag for save prompt
    {
        get
        {
            ....
        }
    }
} 
[Serializable]
public class ChartGroup : INotifyPropertyChanged
{ ... //various properties }

DependencyProperty设置如下(名为Tree,它是ChartGroupCollection的实例):

public static readonly DependencyProperty TreeProperty = DependencyProperty.Register("Tree", typeof(ChartGroupCollection), typeof(ChartsControl), new PropertyMetadata(OnTreeChanged));
    public ChartGroupCollection Tree
    {
        get { return (ChartGroupCollection)GetValue(TreeProperty); }
        set { SetValue(TreeProperty, value); }
    }
 private static void OnTreeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var Treee = sender as ChartsControl;
        if (e.OldValue != null)
        {
            var coll = (INotifyCollectionChanged)e.OldValue;
            coll.CollectionChanged -= Tree_CollectionChanged;
        }
        if (e.NewValue != null)
        {
            var coll = (ObservableCollection<ChartGroup>)e.NewValue;
            coll.CollectionChanged += Tree_CollectionChanged;
        }
    }
    private static void Tree_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        (sender as ChartsControl).OnTreeChanged();
    }
    void OnTreeChanged()
    {
        MessageBox.Show("Do something...");  //RefreshCharts();
    }

我似乎只在创建对象时访问 OnTreeChanged 事件,但是一旦我做了其他工作(添加到 ChartGroup 中的列表或更改 ChartGroup 对象的属性,甚至删除可观察集合的元素,它似乎永远不会触发刷新事件。我已经尝试了其他几种方法来在线找到依赖项属性,但没有解决方案对我有用。我想知道这是归结于我的依赖属性对象的内在性质还是我这边的错误

依赖项属性对象未更新到 UI

Tree_CollectionChanged处理程序中的sender参数不是ChartsControl实例,而是引发 CollectionChanged 事件的集合。

Tree_CollectionChanged方法不应是静态的

private void Tree_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    OnTreeChanged();
}

它应该像这样附加和删除:

private static void OnTreeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    var control = sender as ChartsControl;
    var oldCollection = e.OldValue as INotifyCollectionChanged;
    var newCollection = e.NewValue as INotifyCollectionChanged;
    if (oldCollection != null)
    {
        oldCollection.CollectionChanged -= control.Tree_CollectionChanged;
    }
    if (newCollection != null)
    {
        newCollection.CollectionChanged += control.Tree_CollectionChanged;
    }
}

另请注意,添加 CollectionChanged 处理程序并不关心订阅集合元素的 PropertyChanged 事件。每当在集合中添加或删除元素时,还必须附加或删除 PropertyChanged 处理程序。看看NotifyCollectionChangedEventArgs.Action属性。