0

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?

2 Answers 2

3

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

The code above is in my ViewModel class which I then set as DataSource in my Window_Loaded. Would you mind showing how to use INotifyPropertyChanged? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.