Mikhail Orlov
Mikhail Orlov

Reputation: 2857

How to implement IDataErrorInfo with lambda versions of RaisePropertyChanged in MVVM Light?

Earlier I had:

const string FooPropertyName = "Foo";

And I was doing:

RaisePropertyChanged(FooPropertyName);

I was also implementing the IDataErrorInfo interface like this:

public string this[string columnName]
{
    get
    {
        switch(columnName)
        {
            case FooPropertyName:
                return CheckFoo();

            default: return null;
        }
    }
}

Now that I want to switch to the lambda syntax and omit the string constant,

RaisePropertyChanged(() => Foo);

how can I implement IDataErrorInfo?

Upvotes: 0

Views: 391

Answers (2)

Adi Lester
Adi Lester

Reputation: 25201

You can get the property name in a similar fashion

protected string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
    var memberExpr = propertyExpression.Body as MemberExpression;
    if (memberExpr == null) throw new ArgumentException("propertyExpression should represent access to a member");
    return memberExpr.Member.Name;
}

Then use it like this

if (columnName == GetPropertyName<MyClass>(() => Foo)) 
    return CheckFoo();

Upvotes: 2

Sheridan
Sheridan

Reputation: 69959

I haven't used MVVM Light before, so this is more for informative purposes than for an answer, but I do know that in order to not supply a property name to the INotifyPropertyChanged.PropertyChanged event, you would need to use the CallerMemberNameAttribute Class. According to the linked page, this

Allows you to obtain the method or property name of the caller to the method

However, this attribute was only added in .NET 4.5, so if you're not using this version, then you won't be able to make use of it.

It should be used before the input parameter that you want to automatically supply the member name to... in your case, in the RaisePropertyChanged method:

public override void RaisePropertyChanged([CallerMemberName] string propertyName)
{
    ...
}

Upvotes: 0

Related Questions