tags:

views:

153

answers:

3

I'm using MVVM and within one of my VM's I have an IsEditable property (well they all do from a base class) which is used by a series of buttons to determine whether their commands can fire.

This VM also has a sub VM for which I need to echo this IsEditable property down to, currently I'm overriding my OnPropertyChanged method to check if the property being refreshed is .Equals("IsEditable").

I've got a nagging which is telling me this isn't really good practice, if this IsEditable is renamed in the future then this functionality will break silently. Is there a better way to do this, or to be able to use the property name with reflection, e.g.:

if (propertyRefreshName.Equals(IsEditable.Name))
{
    // Echo down IsEditable change....
}
+2  A: 

You could, potentially, use the same trick with expressions that people use to implement INotifyPropertyChanged. Eric De Carufel blogged about this.

If you use the same technique, you could write your code as:

if (IsPropertyName(() => this.IsEditable, propertyRefreshName))
{ ... }

This would just require implementing a function to check the property name, but let you do it in a way that doesn't use hard coded strings.

Reed Copsey
Your link has `_22` in it that breaks it. Should be http://blog.decarufel.net/2009/07/how-to-use-inotifypropertychanged-type.html
statenjason
Hrm... Both are working for me. The _22 is the revision from the day after...
Reed Copsey
I get "Sorry, the page you were looking for in the blog Eric De C# does not exist" when going to it.
statenjason
very odd - it's working here for me, with no issues.
Reed Copsey
+1  A: 

Try an extension method to get property names off of objects

public static class ObjectExtensions
{
    public static string PropertyName<T,TOut>(this T source, Expression<Func<T,TOut>> property)
    {
        var memberExpression = (MemberExpression) property.Body;
        return memberExpression.Member.Name;
    }
}

Then in your OnPropertyChanged add

if(propertyRefreshName == this.PropertyName(x => x.IsEditable))
  SubVM.IsEditable = IsEditable;
statenjason
A: 

I agree with statenjason.

Unless I'm mistaken, in my own experience I learned that the body of the expression tree is not always a MemberExpression (it can actually be anything) so there is more code needed.

Refer to the GetMemberExpression method in the following code from the FluentNHibernate project:

http://github.com/jagregory/fluent-nhibernate/blob/master/src/FluentNHibernate/Utils/Reflection/ReflectionHelper.cs

celticpride