Tuesday, June 16, 2009

Xpo Properties for Strongly Typed freaks!!!

Because XPbaseObject implements INotifyPropertyChanged property setters need to be implemented using a special way like

public string Name
{
    get
    {
        return name;
    }
    set
    {
        SetPropertyValue("Name", ref name, value);
    }
}

but if you are a strongly typed fun like me the you certainly will not like the string representation of the “Name” as a parameter of SetPropertyValue because if you rename the property then you should explicitly rename the string parameter as well.

I used to write my properties like

private string nameWithReflection;

public string NameWithReflection
{
    get
    {
        return nameWithReflection;
    }
    set
    {
        SetPropertyValue(MethodBase.GetCurrentMethod().Name.Replace("set_", ""), ref nameWithReflection, value);
    }
}

Not very elegant eh?

Of course we can use the approach described at those previous posts Static Reflection and at More Static Reflection

so using the following extension methods

public static class Extensions
{
    public static PropertyInfo GetPropertyInfo(this object target, Expression<Func<object>> property)
    {
        var info = target.GetMemberInfo(property) as PropertyInfo;
        if (info == null) throw new ArgumentException("Member is not a property");

        return info;
    }
    public static MemberInfo GetMemberInfo(this object target, Expression member)
    {
        if (member == null) throw new ArgumentNullException("member");

        var lambda = member as LambdaExpression;
        if (lambda == null) throw new ArgumentException("Not a lambda expression", "member");

        MemberExpression memberExpr = null;


        if (lambda.Body.NodeType == ExpressionType.Convert)
            memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
        else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
            memberExpr = lambda.Body as MemberExpression;

        if (memberExpr == null) throw new ArgumentException("Not a member access", "member");

        return memberExpr.Member;
    }

}

we can write our properties like

public string NameWithReflection
{
    get
    {
        return nameWithReflection;
    }
    set
    {
        SetPropertyValue(this.GetPropertyInfo(()=>NameWithReflection).Name, ref nameWithReflection, value);
    }
}
public XPCollection<Order> Orders
{
    get
    {
        return GetCollection<Order>(this.GetPropertyInfo(()=>Orders).Name);
    }
}

Subscribe to XAF feed
Subscribe to community feed

DiggIt!

1 comment: