我有一个使用MVVM模式的应用程序,我想在用户填写信息时实现验证。例如,如果min大于max,我想在视图中禁用该按钮。
我在模型中实现了IDataErrorInfo。这是我的模特:
public class MyModel : IDataErrorInfo, INotifyPropertyChanged
{
private string stock;
public string Stock
{
get { return stock; }
set { stock = value; }
}
private double min;
public double Min
{
get { return min; }
set { min = value; OnPropertyChange("Min"); }
}
private double max;
public double Max
{
get { return max; }
set { max = value; OnPropertyChange("Max"); }
}
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string error = string.Empty;
if (columnName == "Min" || columnName == "Max")
{
if (Min > Max)
{
error = "Min can't be greater than Max";
}
}
return error;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChange(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
我的ViewModel有一个MyModel(绑定到DataGrid)的集合和一个名为CanUpdate的布尔属性。在我的视图中,此CanUpdate绑定到更新按钮的IsEnabled属性。
public class MyViewModel : INotifyPropertyChanged
{
private ObservableCollection<MyModel> stocks;
public ObservableCollection<MyModel> Stocks
{
get { return stocks; }
set { stocks = value; }
}
private bool canUpdate = true;
public bool CanUpdate
{
get { return canUpdate; }
set { canUpdate = value; }
}
public MyViewModel()
{
AddStocks();
}
public void AddStocks()
{
Stocks = new ObservableCollection<MyModel>();
Stocks.Add(new MyModel() { Stock ="Stock 1", Min = 10, Max=20 });
Stocks.Add(new MyModel() { Stock = "Stock 2", Min = 5, Max = 15 });
Stocks.Add(new MyModel() { Stock = "Stock 3", Min = 6, Max = 25 });
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChange(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
用户可以编辑DataGrid中的Min和Max值。在MyModel中引发错误时编辑时必须更新MyViewModel中的CanUpdate属性。请指导我实现这一目标。
答案 0 :(得分:1)
在视图模型中,将项目添加到其PropertyChanged
事件的集合挂钩时。在处理程序中分析Error
属性并相应地修改CanUpdate
。