1

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....
}
dtb
  • 213,145
  • 36
  • 401
  • 431
ChrisFletcher
  • 1,010
  • 2
  • 14
  • 31
  • Using reflection in time critical code is usually not a good idea because it can be very slow. It sounds like you will be running this in the UI thread. The slowdown might not be noticeable at first, but over time you may notice your app start to crawl for no obvios reason. I would recommend a notification mechanism like Reed suggests. – Dolphin Dec 04 '09 at 18:00

3 Answers3

3

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
  • 554,122
  • 78
  • 1,158
  • 1,373
1

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
  • 5,140
  • 1
  • 32
  • 36
0

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
  • 516
  • 1
  • 5
  • 9