首页 > 解决方案 > 未重新设置 WPF 时,组合框值不会保持为以前的值

问题描述

我已阅读相关问题,但我的问题仍然存在。我正在尝试从组合框中选择一个数据库连接,如果连接失败,请将组合值切换回前一个。代码:

 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}"/>

问题是当我尝试输入错误的连接字符串时。然后我想将组合值重新选择为前一个,因此根本不更新它,但它不起作用。我试图做 RaisePropertyChanged("SelectedConnStringValue"); 而不是 OnPropertyChanged,但它什么也不做

标签: wpfviewcomboboxbindingpropertychanged

解决方案


使用该SelectionChanged事件并将其分配SelectedItem给以前的 selectedItem。

Dependency Property属性绑定到 Dependency 属性,并且在给定场景中值已更改。control/combobox除非您再次分配 ,否则setter 将无法恢复该值。

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;
        }
    }

推荐阅读