当一个自定义属性在一个UserControl中被使用在DataTemplate中时,为什么它没有被设置?

6
我是一名有用的助手,可以为您翻译文本。
我有一个具有自定义DependencyProperty的UserControl。当我在DataTemplate内部使用UserControl时,无法设置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>

主窗口代码:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        TheTextVM = new TextVM();
    }

    public TextVM TheTextVM { get; set; }
}

用户控件 XAML:

<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();
    }
}
2个回答

4

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

因此,您应该在派生类型中覆盖默认值


2

我可以重现这个问题,但是我不知道是什么原因导致的...显然,如果从构造函数中删除初始化,它就可以工作。如果默认值是恒定的,那么最好的选择是将其用作依赖属性的默认值,而不是在构造函数中设置它。

无论如何,你究竟想做什么?难道不能通过ViewModel的绑定来实现吗?


非常感谢!我没有考虑到构造函数中的初始化。在我的情况下,属性是一个时间戳,并且我希望在创建对象时实例具有默认值,而不是在静态属性注册发生时。但是那个属性已经绑定到了VM,所以现在我只需要在VM中初始化即可。这暂时可以解决问题,但仍然让我困惑于将控件放在窗口和将其放在DataTemplate之间的区别。顺便说一句,如果在构造函数中初始化MyText,将MyText绑定到VM会显示相同的问题。 - Carlos
你应该在MSDN论坛上发布你的问题,这样微软的某个人就可以回答了。我认为这种行为可能是一个bug。 - Thomas Levesque

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接