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

C# 为什么我的自定义WPF控件属性在绑定到视图模型时不能工作?,c#,wpf,custom-controls,C#,Wpf,Custom Controls,我的自定义控件在像这样绑定时无法工作文本块显示我的视图模型属性Test fine,但我的自定义控件显示默认值empty: .Xaml 这就是你的问题: DataContext="{Binding RelativeSource={RelativeSource Self}}" > 父XAML中的绑定在DynamicMenu的DataContext上查找名为Test的属性。这应该是viewmodel,但不幸的是您将其DataContext设置为自身,并且它没有名为Test的属

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

.Xaml

这就是你的问题:

         DataContext="{Binding RelativeSource={RelativeSource Self}}" >
父XAML中的绑定在DynamicMenu的DataContext上查找名为Test的属性。这应该是viewmodel,但不幸的是您将其DataContext设置为自身,并且它没有名为Test的属性

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

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

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

@EdPlunkett测试是我的视图模型的一个属性,测试是一个静态字符串。我没有包括视图模型以保持代码更清晰。是的,我的错误。@EdPlunkett不用担心,我使它更清晰。在输出窗口中是否有任何绑定错误?似乎是关于如何在UserControl上设置DataContext的问题。@ChrisChevalier更干净了,谢谢。很好的完整示例。容易诊断。唯一的问题是,在第一个代码片段中,TextBlock中缺少一个开角括号,但这是无害的。这与删除双向绑定默认值一起解决了我的问题。谢谢
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); }
    }

}
<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}}" >
<TextBlock 
    Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}" 
    />