简体   繁体   English

如何在MVVM Light中使用lambda版本的RaisePropertyChanged实现IDataErrorInfo?

[英]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: 我也在实现IDataErrorInfo接口,如下所示:

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, 现在我想切换到lambda语法并省略字符串常量,

RaisePropertyChanged(() => Foo);

how can I implement IDataErrorInfo ? 我该如何实现IDataErrorInfo

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();

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 . 我以前没有使用MVVM Light,所以这更多是为了提供信息而不是答案,但我知道为了INotifyPropertyChanged.PropertyChanged事件提供属性名称,您需要使用CallerMemberNameAttribute 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. 但是,此属性仅在.NET 4.5中添加,因此如果您不使用此版本,那么您将无法使用它。

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: 它应该在您要自动提供成员名称的输入参数之前使用...在您的情况下,在RaisePropertyChanged方法中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM