XAML 绑定对依赖项不起作用 属性?

XAML binding not working on dependency property?

我正在尝试(但失败了)对 xaml 中的依赖项 属性 进行数据绑定。当我在后面使用代码时它工作得很好,但在 xaml.

中却不行

用户控件只是一个绑定到依赖项 属性:

TextBlock
<UserControl x:Class="WpfTest.MyControl" [...]>
     <TextBlock Text="{Binding Test}" />
</UserControl>

依赖项属性是一个简单的字符串:

public static readonly DependencyProperty TestProperty 
= DependencyProperty.Register("Test", typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT"));

public string Test
{
    get { return (string)GetValue(TestProperty); }
    set { SetValue(TestProperty, value); }
}

我有一个常规的 属性,在 window 中通常执行 INotifyPropertyChanged

private string _myText = "default";
public string MyText
{
   get { return _myText; }
   set {  _myText = value; NotifyPropertyChanged(); }
}

到目前为止一切顺利。如果我将此 属性 绑定到主 window 上的 TextBlock,则一切正常。如果 MyText 更改并且世界上一切都很好,则文本会正确更新。

<TextBlock Text="{Binding MyText}" />

但是,如果我在我的用户控件上做同样的事情,什么也不会发生。

<local:MyControl x:Name="TheControl" Test="{Binding MyText}" />

现在有趣的是,如果我在后面的代码中进行完全相同的绑定,它就会起作用!

TheControl.SetBinding(MyControl.TestProperty, new Binding
{
    Source = DataContext,
    Path = new PropertyPath("MyText"),
    Mode = BindingMode.TwoWay
});

为什么它在 xaml 中不起作用?

依赖项 属性 声明必须如下所示:

public static readonly DependencyProperty TestProperty =
    DependencyProperty.Register(
        nameof(Test),
        typeof(string),
        typeof(MyControl),
        new PropertyMetadata("DEFAULT"));

public string Test
{
    get { return (string)GetValue(TestProperty); }
    set { SetValue(TestProperty, value); }
}

UserControl 中的绑定 XAML 必须将控件实例设置为源对象,例如通过设置绑定的 RelativeSource 属性:

<UserControl x:Class="WpfTest.MyControl" ...>
     <TextBlock Text="{Binding Test,
         RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</UserControl>

同样重要的是,从不 在其构造函数中设置 UserControl 的 DataContext。我确定有类似

的内容
DataContext = this;

删除它,因为它有效地阻止了从 UserConrol 的父级继承 DataContext。

通过在后面的代码中的 Binding 中设置 Source = DataContext 来明确设置绑定源,而在

<local:MyControl Test="{Binding MyText}" />

绑定源隐式为当前 DataContext。但是,该 DataContext 已通过 UserControl 的构造函数中的分配设置为 UserControl 本身,而不是从 window.

继承的 DataContext(即视图模型实例)