0

我试图让附加属性在后面的代码中工作,但我显然遗漏了一些东西。据我了解,结果应该是“测试”,但它是 string.Empty。

LogicalTreeHelper 声明它child是 的子parent节点,因此树的设置正确。

有什么建议么?

public partial class MainWindow : Window
{
    public MainWindow()
    {
        var parent = new TestParent();
        var child = new Child();
        parent.AddLogicalChild(child);
        parent.SetValue(TestParent.TestProperty, "test");

        var result = child.GetValue(TestParent.TestProperty); // Returns ""

        InitializeComponent();
    }
}


class TestParent : FrameworkElement
{
    public static readonly DependencyProperty TestProperty = 
        DependencyProperty.RegisterAttached("Test", typeof(string), typeof(TestParent), 
        new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.Inherits));

    public void AddLogicalChild(FrameworkElement element)
    {
        base.AddLogicalChild(element);
    }
}

class Child : FrameworkElement
{

}
4

1 回答 1

0

像这样设置逻辑树是行不通的。LogicalChildren在调用 AddLogicalChild 后,您可以通过查看父级的属性轻松地检查这一点。它仍然是null。您可能需要查看如何:覆盖逻辑树

但是,您的继承属性运行良好:

var parent = new StackPanel();
var child = new TextBlock();
parent.Children.Add(child);
parent.SetValue(TestParent.TestProperty, "test");

var result = child.GetValue(TestParent.TestProperty); // returns "test"
于 2013-04-24T06:54:12.630 回答