我正在阅读最新的Prism 4 drop的源代码,我对解决这个问题很感兴趣。 ViewModels有一个基类,它实现了INotifyPropertyChanged和INotifyDataErrorInfo,并提供了一些重构友好的更改通知。
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpresssion)
{
var propertyName = ExtractPropertyName(propertyExpresssion);
this.RaisePropertyChanged(propertyName);
}
private string ExtractPropertyName<T>(Expression<Func<T>> propertyExpresssion)
{
if (propertyExpresssion == null)
{
throw new ArgumentNullException("propertyExpression");
}
var memberExpression = propertyExpresssion.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("The expression is not a member access expression.", "propertyExpression");
}
var property = memberExpression.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException("The member access expression does not access property.","propertyExpression");
}
if (!property.DeclaringType.IsAssignableFrom(this.GetType()))
{
throw new ArgumentException("The referenced property belongs to a different type.", "propertyExpression");
}
var getMethod = property.GetGetMethod(true);
if (getMethod == null)
{
// this shouldn't happen - the expression would reject the property before reaching this far
throw new ArgumentException("The referenced property does not have a get method.", "propertyExpression");
}
if (getMethod.IsStatic)
{
throw new ArgumentException("The referenced property is a static property.", "propertyExpression");
}
return memberExpression.Member.Name;
}
以及它的用法示例
private void RetrieveNewQuestionnaire()
{
this.Questions.Clear();
var template = this.questionnaireService.GetQuestionnaireTemplate();
this.questionnaire = new Questionnaire(template);
foreach (var question in this.questionnaire.Questions)
{
this.Questions.Add(this.CreateQuestionViewModel(question));
}
this.RaisePropertyChanged(() => this.Name);
this.RaisePropertyChanged(() => this.UnansweredQuestions);
this.RaisePropertyChanged(() => this.TotalQuestions);
this.RaisePropertyChanged(() => this.CanSubmit);
}
我的问题是这个。如何将属性名称数组传递给重载方法(RaisePropertyChanged)并将最后一行代码从4行压缩为1?
谢谢你, 斯蒂芬
答案 0 :(得分:5)
您是否考虑过更改:
protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpresssion)
{
var propertyName = ExtractPropertyName(propertyExpresssion);
this.RaisePropertyChanged(propertyName);
}
到:
protected void RaisePropertyChanged<T>(params Expression<Func<T>>[] propertyExpresssion)
{
foreach (var propertyName in
propertyExpresssion.Select(ExtractPropertyName))
{
this.RaisePropertyChanged(propertyName);
}
}
,用法是:
private void RetrieveNewQuestionnaire()
{
//yada yada yada
this.RaisePropertyChanged(() => this.Name,
() => this.UnansweredQuestions,
() => this.TotalQuestions);
}
也许有人认为这是一种不好的做法,但至少要做到这一点。 祝你好运。