当绑定数据更改时,用户控件的依赖性 属性 不更新 属性

Dependency Property on a user control not updating the property when bound data changes

我看到其他人偶尔也有这个问题,我能说的最好的是我已经复制了他们修复的几个变体,但还没有让它起作用。

我知道我的绑定数据正在发送正确的 INotify 事件,因为我可以将其他控件绑定到数据,如文本块,并看到它的内容随着对象 属性 的变化而变化,但我的用户控件似乎不是完全接收事件。

public partial class MappingSelector : UserControl
{
    public Type OutputDriver
    {
        get { return (Type)GetValue(OutputDriverProperty); }
        set { Console.WriteLine(value.ToString()); SetValue(OutputDriverProperty, value); UpdateUI(); }
    }

    // Using a DependencyProperty as the backing store for OutPutDriver.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty OutputDriverProperty =
        DependencyProperty.Register("OutputDriver", typeof(Type), typeof(MappingSelector), new PropertyMetadata(null));
    public MappingSelector()
    {
        InitializeComponent();
        (this.Content as FrameworkElement).DataContext = this;
        //UpdateUI();
    }
}

setter 有一个永远不会触发的控制台跟踪,所以我相信 属性 永远不会被设置。

然后我使用以下方式绑定到它:

<root:MappingSelector OutputDriver="{Binding LoadedProfile.UsedDriverInterface, ElementName=page, UpdateSourceTrigger=PropertyChanged}"/>

而且我知道 LoadedProfile.UsedDriverInterface 正在更新和发送正确的事件,因为我也有这个工作正常:

<TextBlock Text="{Binding LoadedProfile.UsedDriverInterface, ElementName=page, UpdateSourceTrigger=PropertyChanged}"/>

后期编辑: 这行得通,但这真的是我需要做的吗?有没有更好的办法? 将此添加到用户控件构造函数;

        var OutputDriverDPD = DependencyPropertyDescriptor.FromProperty(OutputDriverProperty, typeof(MappingSelector));
        OutputDriverDPD.AddValueChanged(this, (sender, args) =>
        {
            OutputDriver = (Type)GetValue(OutputDriverProperty);
        });

The setter has a console trace that never fires so I am confident that the property is never being set.

这是一个陷阱。您定义的 属性 getter 和 setters 是为了 您的 方便。 WPF 框架不会调用它们,它会直接使用依赖项 属性。永远不要在那些你需要完成的吸气剂和 setter 中做任何事情。

如果您想对 属性 更改做出反应,请使用您已经发现的回调。您的控制台跟踪应该在那里,而不是 setter.