Xaml 行为 DP 未更新

Xaml Behavior DP not updated

我有一个使用托管 UWP 行为 SDK 的 UWP 应用程序。 我写了一个自定义行为,它有两个依赖属性,其中一个是 ObservableCollection。

每当我更新集合中的项目时,我都会确保为集合调用 PropertyChanged。

但是,依赖项 属性 没有更新。

我的代码:

<trigger:CustomBehavior ItemIndex="{x:Bind ItemIndex}"
     Presences="{Binding ElementName=Box,
         Path=DataContext.CustomCollection,
             UpdateSourceTrigger=PropertyChanged, Converter={StaticResource TestConverter}}" />

我的 TestConverter 告诉我,当我更新集合中的项目时,updatesource 触发器正在工作。然而,我行为中的依赖项 属性 并未触发 Changed 事件。当我更改整个自定义集合时,DP 会更新,当我只更改一个项目时,它不会。

目前的研究表明,DependencyObject.SetValue 只是检查对象是否发生了变化,如果某个项目发生了变化,它只会认为集合根本没有发生变化?这是真的吗?如果是,我该如何克服?

谢谢

集合类型依赖项 属性 通常应声明为最基本的集合类型 IEnumerable。通过这种方式,您可以将各种实际集合类型分配给 属性,包括那些实现 INotifyCollectionChanged 的集合类型,例如 ObservableCollection<T>.

您将在运行时检查集合类型是否实际实现了接口,并可能附加和分离 CollectionChanged 事件的处理程序方法。

public class CustomBehavior : ...
{
    public static readonly DependencyProperty PresencesProperty =
        DependencyProperty.Register(
            "Presences", typeof(IEnumerable), typeof(CustomBehavior),
            new PropertyMetadata(null,
                (o, e) => ((CustomBehavior)o).OnPresencesPropertyChanged(e)));

    private void OnPresencesPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        var oldCollectionChanged = e.OldValue as INotifyCollectionChanged;
        var newCollectionChanged = e.NewValue as INotifyCollectionChanged;

        if (oldCollectionChanged != null)
        {
            oldCollectionChanged.CollectionChanged -= OnPresencesCollectionChanged;
        }

        if (newCollectionChanged != null)
        {
            newCollectionChanged.CollectionChanged += OnPresencesCollectionChanged;
            // in addition to adding a CollectionChanged handler, any
            // already existing collection elements should be processed here
        }
    }

    private void OnPresencesCollectionChanged(
        object sender, NotifyCollectionChangedEventArgs e)
    {
        // handle collection changes here
    }
}