【问题标题】:AttachedProperty not propagating to children?附加属性不会传播给孩子?
【发布时间】:2010-07-16 11:44:39
【问题描述】:

尝试为 WPF DependencyObject 创建我自己的自定义 AttachedProperty 未能真正做到我想要它做的事情,我有点担心我(再次)没有完全理解 WPF 概念。

我做了一个非常简单的测试类来显示我的问题所在。从the MSDN Documentation,我复制了

public class TestBox : TextBox
{
    public static readonly DependencyProperty IsBubbleSourceProperty = DependencyProperty.RegisterAttached(
            "IsBubbleSource",
            typeof(Boolean),
            typeof(TestBox)
            );
    public static void SetIsBubbleSource(UIElement element, Boolean value)
    {
        element.SetValue(IsBubbleSourceProperty, value);
    }
    public static Boolean GetIsBubbleSource(UIElement element)
    {
        return (Boolean)element.GetValue(IsBubbleSourceProperty);
    }
    public Boolean IsBubbleSource
    {
        get
        {
            return (Boolean)GetValue(IsBubbleSourceProperty);
        }
        set
        {
            SetValue(IsBubbleSourceProperty, value);
        }
    }
}

现在,将我的新的时髦的 TextBox 放入这样的网格中

<Grid vbs:TestBox.IsBubbleSource="true">
    <vbs:TestBox x:Name="Test" Text="Test" >                    
    </vbs:TestBox>
</Grid>

我希望每个未设置 IsBubbleSource 属性本身的孩子都从其父网格“继承”它。它不这样做; MessageBox.Show(Test.IsBubbleSource.ToString()) 显示“假”。附加属性设置为 true。我使用 OnPropertyChanged 事件处理程序检查了这一点。我错过了什么吗?

谢谢!

【问题讨论】:

    标签: c# wpf xaml dependency-properties


    【解决方案1】:

    默认情况下,附加属性不会被继承。您必须在定义属性时指定它:

    public static readonly DependencyProperty IsBubbleSourceProperty = DependencyProperty.RegisterAttached(
        "IsBubbleSource",
        typeof(Boolean),
        typeof(TestBox),
        new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits)
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-14
      • 2020-09-17
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多