如何使附加属性在代码隐藏中工作

时间:2013-04-24 05:08:51

标签: wpf code-behind attached-properties

我正在尝试将附加属性用于后面的代码,但我显然遗漏了一些东西。据我所知,结果应该是“test”,但它是string.Empty。

LogicalTreeHelper指出childparent的子项,因此树设置正确。

有什么建议吗?

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
{

}

1 个答案:

答案 0 :(得分:0)

设置这样的逻辑树不起作用。在调用AddLogicalChild之后,您可以通过查看父级LogicalChildren属性来轻松检查。它仍然是null。您可能需要查看How to: Override the Logical Tree

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

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"