【问题标题】:How do I get attached properties to work in code-behind如何让附加属性在代码隐藏中工作
【发布时间】:2013-04-24 05:08:50
【问题描述】:

我正在尝试让附加属性在后面的代码中工作,但我显然遗漏了一些东西。据我了解,结果应该是“测试”,但它是 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
{

}

【问题讨论】:

    标签: wpf code-behind attached-properties


    【解决方案1】:

    这样设置逻辑树是行不通的。在调用 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 2010-12-16
      相关资源
      最近更新 更多