简体   繁体   English

WPF ComboBox (with IsEditable) - 防止从选项列表中删除所选项目

[英]WPF ComboBox (with IsEditable) - Prevent selected item from being deleted when removed from the list of choices

I have a ComboBox with IsEditable set to true.我有一个IsEditable设置为 true 的ComboBox If I type in a custom option and then reset the list of choices (or even remove all choices), the displayed text does not change.如果我输入自定义选项然后重置选项列表(甚至删除所有选项),显示的文本不会改变。 Which is exactly what I want.这正是我想要的。 However if I select or type in an option that is on the list and then later remove that option from the list, the selected text gets reset to null or empty string.但是,如果我选择或键入列表中的选项,然后从列表中删除该选项,则所选文本将重置为 null 或空字符串。 In this second instance I'd like the selected text to not change (essentially turn into a custom entry).在第二个实例中,我希望所选文本不会更改(基本上变成自定义条目)。

I tried using the SourceUpdated and setting Handled to true but the event doesn't trigger whether I try replacing it with a new ObservableCollection or calling Clear .我尝试使用SourceUpdated并将Handled设置为 true ,但无论我尝试用新的 ObservableCollection 替换它还是调用Clear ,事件都不会触发。

Additionally manually managing the value is problematic because of delayed events triggering on the control itself in response to the change.此外,手动管理该值是有问题的,因为延迟事件会在控件本身上触发以响应更改。 If I use the following code the control responds to the updated list (and resets the value) after everything has finished executing.如果我使用以下代码,则控件会在所有内容执行完毕后响应更新的列表(并重置值)。

string holdValue = SelectedListString;
ListOptions.Clear();
SelectedListString = holdValue;

This is a "nice to have" so I'm hoping for a simple solution and can't use 3rd party libraries for it.这是一个“很高兴拥有”,所以我希望有一个简单的解决方案,并且不能使用 3rd 方库。 Worst case I guess I can do some hacky change tracking that then prevents the value from being modified when the setter is called on the dependency property SelectedListString , but I was hoping for something simpler.最坏的情况,我想我可以做一些 hacky 更改跟踪,然后防止在依赖属性SelectedListString上调用 setter 时修改值,但我希望有更简单的东西。

You can bind your 'SelectedListString' property with 'Text' property of the 'ComboBox' like this您可以像这样将“SelectedListString”属性与“ComboBox”的“Text”属性绑定

<ComboBox IsEditable="True"
          ItemsSource="{Binding ListOptions}"
          SelectedItem="{Binding SelectedListString}"
          Text="{Binding SelectedListString}"/>

And when you clear the list, you hold on the value manually like you did当您清除列表时,您会像以前一样手动保留该值

string holdValue = SelectedListString;
ListOptions.Clear();
SelectedListString = holdValue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM