views:

51

answers:

2

Is it possible to get the decorated class' type inside of the custom attribute's class? For example:

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false)]
public class ViewAttribute : ExportAttribute
{

    public object TargetRegion { get; set; }
    public Type ViewModel { get; set; }
    public Type Module { get; set; }

    public ViewAttribute()
        : base(typeof(UserControl))
    {
        Module = GetDecoratedClassType(); //I need this method
    }
}

In the following example GetDecoratedClassType() would return HomeView

[View]
HomeView MyHomeView { get; set; }
+2  A: 

Couldn't you add it as an argument in the constructor?

public class ViewAttribute : ExportAttribute
{    
    public object TargetRegion { get; set; }
    public Type ViewModel { get; set; }
    public Type Module { get; set; }

    public ViewAttribute(Type decoratedClassType)
        : base(typeof(UserControl))
    {
        Module = decoratedClassType
    }
}

[View(typeof(HomeView))]
HomeView MyHomeView { get; set; }

I know it's not exactly elegant, but would that suffice? (And you should probably make the setter for Module private)

Charles
A: 

See this answer, i tend to agree, at the point of reflection you should have access to the member info that the attribute is applied to.

Rohan West