我有一个 MyViewModel ,其中包含标量属性和集合属性。
public class MyViewModel :
System.ComponentModel.INotifyPropertyChanged,
System.ComponentModel.IDataErrorInfo
{
public MyViewModel()
{
List<SelectableObject> list = new List<SelectableObject>();
foreach (var weekDay in System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames)
{
list.Add(new SelectableObject() { Name = weekDay, IsSelected = false });
}
WeekDays = list;
}
public string Catalog { get; set; }
public DateTime CreationTime { get; set; }
public DateTime ModificationTime { get; set; }
public IEnumerable<SelectableObject> WeekDays { get; private set; }
public ICommand SaveCommand { get; private set; }
public string Error
{
get { return string.Empty; }
}
public string this[string columnName]
{
get
{
var errorResult = string.Empty;
switch (columnName)
{
case "CreationTime":
// Validation logic
break;
case "ModificationTime":
// Validation logic
break;
default:
break;
}
return errorResult;
}
}
}
SelectableObject 类:
public class SelectableObject : System.ComponentModel.INotifyPropertyChanged
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
我想通过 SaveCommand 操纵&lt; Button /&gt; 的 IsEnabled 属性,我希望它只会在表格上没有错误。但我无法弄清楚如何验证这一点:必须选择至少一个WeekDay。
是的,我可以收听 WeekDays 集合中每个对象的 PropertyChanged 事件,但在这种情况下,验证逻辑将与 IDataErrorInfo分开界面。
这个问题有解决办法吗?如何将集合的验证逻辑放入 IDataErrorInfo 接口?
答案 0 :(得分:1)
只需在你的canexecute中做你的逻辑吗?
视图模型:
private DelegateCommand _save;
public ICommand SaveCommand
{
get {return this._save ?? (this._save = new DelegateComamnd(this.MyExecuteMethod, this.MyCanExecuteMethod));}
}
private bool MyCanExecuteMethod()
{
return this.WeekDays.Any(x=>x.IsSelected) && string.IsNullOrWhiteSpace(this.Error);
}
ps:如果有任何错误,错误应该是非空的。