Hasan H
Hasan H

Reputation: 141

WPF prevent combobox selection change under condition

I have a ComboBox who's selected index is binded into an integer. What I am trying to do is to prevent the combobox selection from changing if a certain condition is not met. Here's what I have so far

In xaml:

<ComboBox SelectedIndex="{Binding CurrentMinCondition,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
    <ComboBoxItem>NA</ComboBoxItem>
    <ComboBoxItem>LT</ComboBoxItem>
    <ComboBoxItem>GT</ComboBoxItem>
</ComboBox>

In cs:

private int _currentMinCondition = 0;
public int CurrentMinCondition
{
    get { return _currentMinCondition; }
    set
    {
        if (/*Condition is met*/){
            _currentMinCondition = value;
            OnPropertyChanged("CurrentMinCondition");
        }
        else
        {
            MessageBox.Show("Error");
            _currentMinCondition = 0;
            OnPropertyChanged("CurrentMinCondition");
        }
    }
}

Now I thought this would work but what happens is that when I change my selection from the combo box and the condition is not met, my MessageBox shows an error but the graphical combobox changes its selection. How can I prevent this from happening?

Upvotes: 0

Views: 777

Answers (1)

You can use error validations. In the case that the result is not the expected you can return a bad validation result:

    <ComboBox SelectedIndex="{Binding CurrentMinCondition,Mode=TwoWay,
              UpdateSourceTrigger=PropertyChanged, 
              ValidateOnDataErrors=True, 
              NotifyOnValidationError=True,
              ValidatesOnExceptions=True}",
              Validation.Error="MethodToValidate">

                     <ComboBoxItem>NA</ComboBoxItem>
                     <ComboBoxItem>LT</ComboBoxItem>
                     <ComboBoxItem>GT</ComboBoxItem>
   </ComboBox>

In the properties you should throw the exception:

public int CurrentMinCondition
{
    get {return _currentMinCondition;}
    set 
    {
       if(value != _currentMinCondition)
       {
          if(condition met)
             throw new Exception("Message error");
          else
          {
             _currentMinCondition = value;
             PropertyChanged("CurrentMinCondition");
          }
       }
    }
}

Then in your validation method:

private void ValidateMethod(object sender, ValidationErrorEventArgs e)
{
    e.Handled = true;
}

This will mark with a rectangle of error the Combobox and the underlying value will not be changed if there is an error.

Upvotes: 1

Related Questions