TransWikia.com

WPF prevent combobox selection change under condition

Stack Overflow Asked by Hasan H on March 8, 2021

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?

One Answer

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.

Correct answer by Jorge Fernandez Herrero on March 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP