Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get properties of a class in WinRT

I am writing a Windows 8 application in C# and XAML. I have a class with many properties of the same type that are set in the constructor the same way. Instead of writing and assignment for each of the properties by hand I want to get a list of all the properties of certain type on my class and set them all in a foreach.

In "normal" .NET I would write this

var properties = this.GetType().GetProperties();
foreach (var property in properties)
{
    if (property.PropertyType == typeof(Tuple<string,string>))
    property.SetValue(this, j.GetTuple(property.Name));
}

where j is a parameter of my constructor. In WinRT the GetProperties() does not exist. Intellisense for this.GetType(). does not show anything useful I could use.

like image 242
Igor Kulman Avatar asked Nov 02 '12 14:11

Igor Kulman


2 Answers

You need to use GetRuntimeProperties instead of GetProperties:

var properties = this.GetType().GetRuntimeProperties();
// or, if you want only the properties declared in this class:
// var properties = this.GetType().GetTypeInfo().DeclaredProperties;
foreach (var property in properties)
{
    if (property.PropertyType == typeof(Tuple<string,string>))
    property.SetValue(this, j.GetTuple(property.Name));
}
like image 128
Thomas Levesque Avatar answered Oct 23 '22 04:10

Thomas Levesque


Try this:

public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo type)
{
    var list = type.DeclaredProperties.ToList();

    var subtype = type.BaseType;
    if (subtype != null)
        list.AddRange(subtype.GetTypeInfo().GetAllProperties());

    return list.ToArray();
}

and use it like this:

var props = obj.GetType().GetTypeInfo().GetAllProperties();

Update: Use this extension method only if GetRuntimeProperties is not available because GetRuntimeProperties does the same but is a built-in method.

like image 45
Rico Suter Avatar answered Oct 23 '22 06:10

Rico Suter