views:

28

answers:

1

Trying to create my own custom AttachedProperty for a WPF DependencyObject failed to actually do what I wanted it to do, and I am a bit worried that I (again) did not understand a WPF concept fully.

I made a very simple test class to show where my problem lies. From the MSDN Documentation, I copied

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);
        }
    }
}

Now, placing my new and funky TextBox into a Grid like this

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

I expected every child that does not set the IsBubbleSource property itself to "inherit" it from its parent grid. It does not do this; a MessageBox.Show(Test.IsBubbleSource.ToString()) shows "false". The attached property is set to true. I checked this using an OnPropertyChanged event handler. Did I miss something?

Thanks!

+2  A: 

By default, attached properties are not inherited. You have to specify it when you define the property:

public static readonly DependencyProperty IsBubbleSourceProperty = DependencyProperty.RegisterAttached(
    "IsBubbleSource",
    typeof(Boolean),
    typeof(TestBox),
    new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits)
    );
Bubblewrap
Yeah, thats it. Thanks! I wonder what use they are if they are not inherited...
Jens