代码之家  ›  专栏  ›  技术社区  ›  Jens

附属财产不向儿童传播?

  •  0
  • Jens  · 技术社区  · 14 年前

    尝试为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);
            }
        }
    }
    

    现在,把我新的时髦的文本框放到这样的网格里

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

    IsBubbleSource 属性本身从其父网格“继承”它。它不这样做;一 MessageBox.Show(Test.IsBubbleSource.ToString())

    谢谢!

    1 回复  |  直到 14 年前
        1
  •  4
  •   Bubblewrap    14 年前

    默认情况下,不会继承附着的属性。定义属性时必须指定它:

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