Jon Erickson
Jon Erickson

Reputation: 114926

Attached Property verboseness

I'm trying to understand what all is going on when I create an attached property.

Are the SetText() and GetText() methods (that are inserted via the snippet/template and that I see in many examples) required? What within the framework is using them?

public static readonly DependencyProperty TextProperty =
    DependencyProperty.RegisterAttached("Text",
                                        typeof(string),
                                        typeof(FundIndexDataHeaderItem),
                                        new PropertyMetadata(default(string)));

public static void SetText(UIElement element, string value)
{
    element.SetValue(TextProperty, value);
}

public static string GetText(UIElement element)
{
    return (string)element.GetValue(TextProperty);
}

Could I replace those methods with a simple property, so that I can get/set through a property instead of using those methods?

public string Text
{
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}

Upvotes: 3

Views: 74

Answers (1)

brunnerh
brunnerh

Reputation: 185225

They are just for your convenience, the framework does not use them.

You cannot do the latter as you need to somehow pass the instance on which the property is set, as the property is attached you do not have the instance as this.

Upvotes: 4

Related Questions