pixel
pixel

Reputation: 10547

WPF How to disable a button if validation on TextBox fails

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

Answers (2)

Justin CI
Justin CI

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

Alan McBee
Alan McBee

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.

  1. In the ButtonEnabled property getter, return true if the Age property value is in the right range, false otherwise.

-OR-

  1. In the Age property setter, set or clear the ButtonEnabled property, depending whether the value is in the right range.

Upvotes: 2

Related Questions