WPF如何在文本框验证失败时禁用按钮
我有一个带有文本框的表单,可以保存年龄。我实现了如下验证: 在我的ViewModel中,我有属性年龄:WPF如何在文本框验证失败时禁用按钮,wpf,xaml,Wpf,Xaml,我有一个带有文本框的表单,可以保存年龄。我实现了如下验证: 在我的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
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;
}
}
私人浮动年龄;
公众浮动年龄{
获取{返回年龄;}
设置
{
如果(值120)
{
抛出新的ArgumentException(“年龄必须介于0到120岁之间”);
}
年龄=价值;
}
}
我的XAML是:
<TextBox Name="txtAge" Text="{Binding Age, UpdateSourceTrigger=PropertyChanged, StringFormat=N1, ValidatesOnExceptions=True}" />
这一切都很好,如果我输入300岁,我会在我的文本框下显示错误。但是,如果出现错误,如何禁用按钮?您是否使用某种MVVM模式?你应该是。我假设你是,因为你把它叫做ViewModel 将布尔属性添加到ViewModel。将其命名为ButtonneEnabled(使用更好的名称)。确保它正确使用INotifyPropertyChanged.PropertyChanged事件 以单向绑定方式将按钮的
IsEnabled
属性绑定到ViewModel的ButtonneEnabled属性
您可以选择如何设置ButtonEnabled
您是否在使用某种MVVM模式?你应该是。我假设你是,因为你把它叫做ViewModel 将布尔属性添加到ViewModel。将其命名为ButtonneEnabled(使用更好的名称)。确保它正确使用INotifyPropertyChanged.PropertyChanged事件 以单向绑定方式将按钮的
IsEnabled
属性绑定到ViewModel的ButtonneEnabled属性
您可以选择如何设置ButtonEnabled
如果您使用的是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;
}
public ICommand和RemoveCommand
{
得到
{
if(this.removeCommand==null)
{
this.removeCommand=new RelayCommand(this.ExecuteRemoveCommand,this.CanExecuteRemoveCommand);
}
返回此.removeCommand;
}
}
私有void ExecuteMoveCommand(对象obj)
{
}
私有布尔CANEXECUTEREMOVERCOMMAND(对象obj)
{
如果(120岁)
{
返回false;
}
返回true;
}
如果您使用的是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;
}
public ICommand和RemoveCommand
{
得到
{
if(this.removeCommand==null)
{
this.removeCommand=new RelayCommand(this.ExecuteRemoveCommand,this.CanExecuteRemoveCommand);
}
返回此.removeCommand;
}
}
私有void ExecuteMoveCommand(对象obj)
{
}
私有布尔CANEXECUTEREMOVERCOMMAND(对象obj)
{
如果(120岁)
{
返回false;
}
返回true;
}
上面的代码在我的ViewModel类中,然后我在加载的窗口中将其设置为数据源。您介意演示如何使用INotifyPropertyChanged吗?谢谢查看DemoCustomer
类。上面的代码在我的ViewModel类中,然后在我的窗口中设置为DataSource。您介意演示如何使用INotifyPropertyChanged吗?谢谢查看DemoCustomer
类。