为什么在DataTemplate中使用控件时未设置UserControl中的自定义属性?

Car*_*los 5 wpf user-controls dependency-properties datatemplate

我有一个自定义的UserControl DependencyProperty.当我从里面使用UserControl时DataTemplate,我无法设置值DependencyProperty.如果我直接在窗口中使用UserControl,那么DependencyProperty工作正常.我为长篇文章道歉,我将代码简化为最小化,仍然显示我在项目中遇到的问题.感谢您的帮助,我不知道还有什么可以尝试的.

主窗口XAML:

<Window ...>
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:TextVM}">
            <local:TextV MyText="I do not see this"/> <!--Instead I see "Default in Constructor"-->
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Border BorderThickness="5" BorderBrush="Black" Width="200" Height="100" >
            <StackPanel>
                <ContentControl Content="{Binding Path=TheTextVM}"/>
                <local:TextV MyText="I see this"/>
            </StackPanel>
        </Border>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

主窗口代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        TheTextVM = new TextVM();
    }

    public TextVM TheTextVM { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

UserControl XAML:

<UserControl ...>
    <Grid>
        <TextBlock x:Name="textBlock"/>
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

用户控制代码:

public partial class TextV : UserControl
{
    public TextV()
    {
        InitializeComponent();
        MyText = "Default In Constructor";
    }

    public static readonly DependencyProperty MyTextProperty =
       DependencyProperty.Register("MyText", typeof(string), typeof(TextV),
       new PropertyMetadata("", new PropertyChangedCallback(HandleMyTextValueChanged)));

    public string MyText
    {
        get { return (string)GetValue(MyTextProperty); }
        set { SetValue(MyTextProperty, value); }
    }

    private static void HandleMyTextValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
    {
        TextV tv = d as TextV;
        if(tv != null) tv.textBlock.Text = args.NewValue.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 4

您在代码中设置的值的优先级高于在 XAML 中设置的任何值。

相反,您应该覆盖派生类型中的默认值