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

Wpf 在DataTemplate中使用UserControl时,为什么不设置该控件中的自定义属性?,wpf,user-controls,datatemplate,dependency-properties,Wpf,User Controls,Datatemplate,Dependency Properties,我有一个用户控件,它有一个自定义的dependencProperty。当我从数据模板中使用UserControl时,我无法设置DependencyProperty的值。如果我在窗口中直接使用UserControl,则dependencProperty可以正常工作。我为这篇长篇大论道歉,我将代码简化到了最低限度,这仍然显示了我在项目中存在的问题。谢谢你的帮助,我不知道还能尝试什么 主窗口XAML: <Window ...> <Window.Resources>

我有一个用户控件,它有一个自定义的
dependencProperty
。当我从
数据模板中使用UserControl时,我无法设置
DependencyProperty的值。如果我在窗口中直接使用UserControl,则
dependencProperty
可以正常工作。我为这篇长篇大论道歉,我将代码简化到了最低限度,这仍然显示了我在项目中存在的问题。谢谢你的帮助,我不知道还能尝试什么

主窗口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>
UserControl XAML:

<UserControl ...>
    <Grid>
        <TextBlock x:Name="textBlock"/>
    </Grid>
</UserControl>

我可以重现这个问题,但我不知道是什么引起的。。。显然,如果您从构造函数中删除初始化,它就会工作。如果默认值是常量,最好的选择是将其用作依赖项属性的默认值,而不是在构造函数中设置它


不管怎样,你到底想做什么?难道不能通过对ViewModel进行绑定来实现吗?

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


相反,你应该这样做。

非常感谢!我没有考虑构造函数中的初始化。在我的例子中,属性是一个时间戳,我希望实例在创建对象时有一个默认值,而不是在发生静态属性注册时。但是该属性无论如何都绑定到一个VM,所以现在我将在VM中初始化它。现在就可以了,但是仍然让我对将控件放入窗口和将其放入DataTemplate之间的区别感到困惑。顺便说一句,如果MyText在构造函数中初始化,那么将MyText绑定到VM也会出现同样的问题。您可能应该在MSDN论坛上发布您的问题,以便MS的人能够回答。我认为这种行为可能是一个错误
<UserControl ...>
    <Grid>
        <TextBlock x:Name="textBlock"/>
    </Grid>
</UserControl>
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();
    }
}