Reputation: 10547
I have a form with TextBox that holds Age. I have implemented validation like this:
In my ViewModel, I have property age:
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;
}
}
My XAML is:
<TextBox Name="txtAge" Text="{Binding Age, UpdateSourceTrigger=PropertyChanged, StringFormat=N1, ValidatesOnExceptions=True}" />
This all works fine and if I enter age 300, I get error showing under my text box. But how do I disable the button in case an error occurs?
Upvotes: 0
Views: 1008
Reputation: 2741
If your are using MVVM then you can disable button in the CanExecute of ICommand
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;
}
Upvotes: 3
Reputation: 4320
Are you using some kind of MVVM pattern? You should be. I'll assume you are, since you called it ViewModel.
Add a Boolean property to the ViewModel. Name it something like ButtonEnabled (use a better name than that). Make sure it is appropriately using the INotifyPropertyChanged.PropertyChanged event.
Bind the IsEnabled
property of the Button to the ButtonEnabled property of the ViewModel, in a OneWay binding.
You have a choice on how to set ButtonEnabled.
-OR-
Upvotes: 2