wpf - 未重新设置 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,但它什么也不做
解决方案
使用该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;
}
}
推荐阅读
- image-processing - Python / Cython 优化(3D 内核过滤器)
- python - 列出来自 functool 部分的装饰器方法
- python - 使用 pandas 函数的方法链接
- laravel - Laravel BackPack 翻译行
- google-cloud-platform - 重命名应用程序/站点以及如何在 Google 登录中更改名称
- security - 如何在 Google Cloud Platform 上监控用户对 Firestore 数据库的访问
- verilog - 使用 Verilog 中的参数获取错误
- mysql - 通过使用 u_d_functions、存储过程等简化具有大量 coalesce(sum()) 的 mysql 视图的查询
- c# - 字符串的正则表达式以数字开头,后跟 + 字符
- list - 在 Microsoft Infopath 中传递查找值