Search code examples
wpfviewcomboboxbindingpropertychanged

Combobox value does not stay as previous value when not re-set WPF


I have read related issues, but my problem still occurs. I am trying to choose a database connection from the combobox and if it fails to connect, switch the combo value back to the previous one. Code:

 public string SelectedConnStringValue
    { 
        get { return _selectedConnStringValue; }
        set
        {
            if (!DBConn.Instance.Open(value))
            {
                System.Windows.MessageBox.Show("Attempt failed", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                DBConn.Instance.Close();
                _selectedConnStringValue = value;
                DefaultConf.Instance.DefaultConnectionStringName = value;
            }
            OnPropertyChanged("SelectedConnStringValue");
        }
    }


    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));

    }

XAML

 <ComboBox x:Name="serversComboBox" SelectedValuePath="Name" DisplayMemberPath="Name" Width="120" Margin="672,0,0,0" Height="25" 
            ItemsSource="{Binding Path=Connections}" Text="{Binding SelectedConnStringValue}"/>

The problem is when I try to put wrong connectionstring. I want then to reselect the combo value to the previous one, thus not updating it at all, but it does not work. I have tried to do RaisePropertyChanged("SelectedConnStringValue"); instead of OnPropertyChanged, but it does nothing


Solution

  • Use the SelectionChanged event and assign the SelectedItem to previous selectedItem.

    Properties are binded to Dependency property and value is already changed in Dependency Property in the given scenario. The setter will not be able to revert the value in control/combobox unless you assign it again.

    private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var comboBox = sender as ComboBox;
            var selctedItem = comboBox?.SelectedItem as TestModel;
            if (selctedItem != null && selctedItem.Equals("Test2"))
            {
                comboBox.SelectedItem = previousSelected;
            }
        }