获取ViewModel中所有数据绑定属性列表的最有效方法是什么。我有一个Window,它有一个ViewModel和多个用户控件,根据用户选择显示。我使用IDataErrorInfo进行验证。我想知道绑定了哪些属性,以便只有在用户单击保存按钮时才能验证这些属性。
下面是我当前的实现,我担心一些属性可能最终会出现在列表中并被错误地验证。
public class ViewModel : IDataErrorInfo
{
private bool _validate = false;
private List<string> _boundProperties = new List<string>();
private void OnPropertyBound(string propertyName)
{
}
public string Property1
{
get { OnPropertyBound("Property1"); return "value1"; }
}
public string Property2
{
get { OnPropertyBound("Property2"); return "value2"; }
}
public string Error
{
get
{
return null;
}
}
public string this[string columnName]
{
get
{
if (!_boundProperties.Contains(columnName)) return null;
if (!_validate) return null; // Set to true when user tries to save. OnPropertyChanged event also fired to refresh the bindings afterwards.
string errorMessage = string.Empty;
switch (columnName)
{
case "Property1":
// Some validation code that sets the errorMessage
break;
case "Property2":
// Some validation code that sets the errorMessage
break;
}
return errorMessage;
}
}
}