Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there attached property in C# itself?

Tags:

c#

wpf

In C# itself, is there something like "attached property" used in WPF?

like image 634
user705414 Avatar asked Jun 23 '11 23:06

user705414


4 Answers

The short answer is no. The slightly longer answer is that this is a bit of an unfortunate story. We designed "extension properties" for C# 4 and got as far as implementing (but not testing) them when we realized, oh, wait, the thing we designed is not really compatible with WPF-style properties. Rather than redesign and reimplement the feature we ended up cutting it.

The even longer version is here:

http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx

like image 60
Eric Lippert Avatar answered Nov 09 '22 04:11

Eric Lippert


AttachedProperties are part of the .NET Framework, not part of the C# language specification, and specifically part of the System.Activities.Presentation.Model namespace, which is WPF specific.

like image 44
Stefan Z Camilleri Avatar answered Nov 09 '22 05:11

Stefan Z Camilleri


In WPF, an attached property allows you to do something like:

<TextBlock Grid.Row="2" Text="I know nothing about grids!" />

This would be like having a class in C# defined as:

public class TextBlock
{
    public string Text { get; set; }
}

And being able to do this:

var tb = new TextBlock();
tb.Grid.Row = 2; // this line would not compile

In order to make this work, you'd need to pass a Grid object into your TextBlock class:

public class TextBlock
{
    public string Text { get; set; }
    public Grid Grid { get; set; }

    public TextBlock(Grid grid)
    {
        Grid = grid;
    }
}

But I don't think there's anything directly equivalent to the way attached properties work in WPF. You'd need to build it by hand.

What are you trying to accomplish?

like image 2
devuxer Avatar answered Nov 09 '22 04:11

devuxer


You can use the ConditionalWeakTable<TKey, TValue> class to attach arbitrary state to an instance. You can combine it with extension methods to create a form of extension properties, but unfortunately without using the nice property syntax in C#.

like image 1
Jordão Avatar answered Nov 09 '22 05:11

Jordão