为什么我的自定义 WPF 控件 属性 在绑定到视图模型时不起作用?

Why wont my custom WPF control property work when bound to a view model?

当我像这样绑定时,我的自定义控件将无法工作(文本块显示我的视图模型 属性 Test 很好,但我的自定义控件显示默认值 empty ):

<local:DynamicMenu Text="{Binding Test}"/>
<TextBlock Text="{Binding Test}"></TextBlock>

如果我有一个静态值,它确实可以工作:

<local:DynamicMenu Text="test"/>
<TextBlock Text="{Binding Test}"></TextBlock>

它是这样实现的。我更喜欢一个能使它像 TextBlock 一样工作的解决方案。

.Xaml.CS

public partial class DynamicMenu : UserControl
{
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text",
            typeof(string),
            typeof(DynamicMenu),
            new FrameworkPropertyMetadata("Empty",
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public DynamicMenu()
    {
        InitializeComponent();
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

}

.Xaml

<UserControl x:Class="Whelen.Griffin.Views.DynamicMenu"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" 
             DataContext="{Binding RelativeSource={RelativeSource Self}}" >
    <TextBlock Text="{Binding Text}"></TextBlock>
</UserControl>

这是你的问题:

         DataContext="{Binding RelativeSource={RelativeSource Self}}" >

父 XAML 中的绑定在 DynamicMenu 的 DataContext 上查找名为 Test 的 属性。那应该是视图模型,但不幸的是,您将其 DataContext 设置为自身,并且它没有 属性 命名的 Test。

永远不要将 UserControl 的 DataContext 设置为 this。这是一个典型的错误。

删除设置 DataContext 的那一行,改为执行以下操作:

<TextBlock 
    Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}" 
    />