Search code examples
wpfattached-properties

Do you have a real world example of AttachedPropertyBrowsableWhenAttributePresentAttribute usage?


I just come across AttachedPropertyBrowsableWhenAttributePresentAttribute, but can't think of when it would be useful. Any ideals?


Solution

  • Browsable means that a designer, like Visual Studio's WPF designer named Cider, shows the property in the designer. Since attached properties are not an actual property of a type and can be applied to almost type it is hard for the designer to know when to show or not show the property. These attributes are a way for a developer to let the designer know a certain attached property should be shown in the designer. In other words: Browsable. This specific attribute lets the designer know that this attached property should be browsable on types that have the specified attribute applied to them.

    The attached property:

    public class WhenAttributePresentTestControl : Grid
    {
        public static readonly DependencyProperty ShowWhenCustomAttributePresentProperty = DependencyProperty.RegisterAttached(
          "ShowWhenCustomAttributePresent",
          typeof(int),
          typeof(WhenAttributePresentTestControl));
    
        public static void SetShowWhenCustomAttributePresent(UIElement element, int value)
        {
            element.SetValue(ShowWhenCustomAttributePresentProperty, value);
        }
    
        [AttachedPropertyBrowsableWhenAttributePresentAttribute(typeof(MyCustomAttribute))]
        public static int GetShowWhenCustomAttributePresent(UIElement element)
        {
            return (int)element.GetValue(ShowWhenCustomAttributePresentProperty);
        }
    }
    

    Usage example:

    [MyCustomAttribute]
    public class CustomLabel : Label
    {
    }
    
    public class CustomLabelNoCustomAttribute : Label
    {
    }
    

    The designer will show the ShowWhenCustomAttributePresent attached property in the property editor for the CustomLabel, but not for CustomLabelNoCustomAttribute.

    Source: http://blogs.msdn.com/jnak/archive/2008/01/17/showing-attached-properties-in-the-cider-wpf-designer.aspx

    Actual usage: I can not find any usage of this attribute in the .Net framework with Reflector.

    Funny side note: Apparently it is also the longest type name of the .Net 3.0 framework