我有一个包含Age的TextBox表单。我已经实现了这样的验证:
在我的ViewModel中,我有属性年龄:
private float age;
public float Age {
get { return age; }
set
{
if (value <= 0 || value > 120)
{
throw new ArgumentException("The age must be between 0 and 120 years");
}
age= value;
}
}
我的XAML是:
<TextBox Name="txtAge" Text="{Binding Age, UpdateSourceTrigger=PropertyChanged, StringFormat=N1, ValidatesOnExceptions=True}" />
这一切都很好,如果我输入300岁,我会在文本框下面显示错误。但是如果发生错误,如何禁用按钮?
答案 0 :(得分:3)
如果您正在使用MVVM,则可以在ICommand的CanExecute中禁用按钮
public ICommand RemoveCommand
{
get
{
if (this.removeCommand == null)
{
this.removeCommand = new RelayCommand<object>(this.ExecuteRemoveCommand, this.CanExecuteRemoveCommand);
}
return this.removeCommand;
}
}
private void ExecuteRemoveCommand(object obj)
{
}
private bool CanExecuteRemoveCommand(object obj)
{
if (Age <= 0 || Age > 120)
{
return false;
}
return true;
}