C# 更改项目源时,“可编辑”组合框将丢失选定值
我有一个可编辑的组合框,如果项目源被更改,当前选定的项目将从项目源中删除,该组合框将释放值 代码如下所示:C# 更改项目源时,“可编辑”组合框将丢失选定值,c#,wpf,combobox,C#,Wpf,Combobox,我有一个可编辑的组合框,如果项目源被更改,当前选定的项目将从项目源中删除,该组合框将释放值 代码如下所示: <ComboBox x:Name="TableNameCombo" MinWidth="100" IsEditable="True" ItemsSource="{Binding TableNames}" SelectionChanged="TableNameCombo_SelectionChanged"
<ComboBox x:Name="TableNameCombo"
MinWidth="100"
IsEditable="True"
ItemsSource="{Binding TableNames}"
SelectionChanged="TableNameCombo_SelectionChanged"
Text="{Binding TableName,
ValidatesOnDataErrors=True,
UpdateSourceTrigger=PropertyChanged}" />
如果更改项目源时我处于不同的视图中,则保留该值。
只有在“带组合框的视图”处于活动状态时更改了itemsource,该值才会丢失。
请帮助我如何保留combobox值,即使它不在itemsource中,并且当view comtaining combobox处于活动状态时,项目源发生了更改
注:
1.我所说的视图是指我有一个选项卡式面板,所有视图都不同
标签
2.我不是说任何回退价值。我只是想
保留所选值的内容,即使该值在中不存在
组合框项目源
让我把问题澄清为非常简单的要求,
这是我的应用程序示例截图
当用户在文本框中输入项目并单击“删除项目”按钮时,该项目将从组合框的itemSource集合中删除。但当我这样做时,该项不会显示在combobox中。
我的要求是,即使项目不在集合中,也要将其保留在组合框中。您可以添加以下代码:
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
public static class ComboBoxItemsSourceDecorator
{
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.RegisterAttached(
"ItemsSource",
typeof(IEnumerable),
typeof(ComboBoxItemsSourceDecorator),
new PropertyMetadata(null, ItemsSourcePropertyChanged));
public static void SetItemsSource(UIElement element, bool value)
{
element.SetValue(ItemsSourceProperty, value);
}
public static IEnumerable GetItemsSource(UIElement element)
{
return (IEnumerable)element.GetValue(ItemsSourceProperty);
}
private static void ItemsSourcePropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs e)
{
var target = element as ComboBox;
if (element == null)
{
return;
}
// Save original binding
var originalBinding = BindingOperations.GetBinding(target, ComboBox.TextProperty);
BindingOperations.ClearBinding(target, ComboBox.TextProperty);
try
{
target.ItemsSource = e.NewValue as IEnumerable;
}
finally
{
if (originalBinding != null)
{
BindingOperations.SetBinding(target, ComboBox.TextProperty, originalBinding);
}
}
}
}
然后像这样使用:
<ComboBox IsTextSearchEnabled="true"
IsTextSearchCaseSensitive="false"
options:ComboBoxItemsSourceDecorator.ItemsSource="{Binding Path=Values, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
Text="{Binding Path = Value}"
IsEditable ="True">
它只是在ItemsSource更改时基本上保留了对同一文本的绑定
注意:使用decorators ItemsSource,而不是buildin。这听起来像是一种黑客行为,而不是解决方案。您的目标是什么?我的目标是在组合框中保留最后选定的值,即使该值已从设置为项目源的集合中删除。Hi@ScottNimrod。我希望现在这个问题很容易理解。