当绑定到ViewModel时,框架默认处理一些验证,例如,如果文本字段绑定到int属性并且用户输入字母,则输入的边框变为红色。我读过IDataErrorInfo
和INotifyDataErrorInfo
,但无法成功实施(这就是我需要的方法)。
所以如果这是我的模特:
public class TestModel : ObservableObject
{
public int ModelId { get; set; }
public string ModelName { get; set; }
private int _modelNumber;
public int ModelNumber
{
get { return _modelNumber; }
set
{
_modelNumber = value;
RaisePropertyChanged();
}
}
}
我的ViewModel:
public class TestViewModel : ObservableObject
{
private TestModel _selectedModel;
public TestModel SelectedModel
{
get { return _selectedModel; }
set
{
_selectedModel = value;
RaisePropertyChanged();
}
}
private ICommand _doSomthingCommand;
public ICommand DoSomthingCommand
{
get
{
if (_doSomthingCommand == null)
{
_doSomthingCommand = new CommandBase(doSomthing, canDosomething);
}
return _doSomthingCommand;
}
}
private bool canDosomething(object arg)
{
//check here if an error exists
}
private void doSomthing(object obj)
{
throw new NotImplementedException();
}
}
我怎么知道视图中有错误并从canexecute方法返回false?
答案 0 :(得分:0)
我自己不是mvvm专家。但我会说你的模型不应该提出属性改变的事件。该属性应该在您的视图模型中。
private int _modelNumber;
public int ModelNumber
{
get { return SelectedModel.ModelNumber; }
set
{
SelectedModel.ModelNumber = value;
RaisePropertyChanged();
}
}
要实现IDataErrorInfo,显然要将其添加为接口
public class TestViewModel : ObservableObject, IDataErrorInfo
并实现界面
public string Error
{
get { return string.Empty; }
}
public string this[string propertyName]
{
get { return GetErrorForProperty(propertyName); }
}
private string GetErrorForProperty(string propertyName)
{
switch (propertyName)
{
case "ModelNumber":
if (test bool property here)
{
//if false
return "string";
}
else
{
//if true
return string.Empty;
}
default:
return string.Empty;
}
在视图绑定中如此:
Text="{Binding ModelNumber, ValidatesOnDataErrors=True}"