简体   繁体   中英

Maintaining combobox text after selecting a bound item in WPF / C#

I have a WPF ComboBox which I'm using to search names. I use the MVVM pattern and it's all pretty simple:

The ComboBox Text property is bound to a "SearchString" property on the VM. The ComboBox ItemsSource is bound to a "SearchResult" property on the VM. This is a list of objects displayed using a DataTemplate. The ComboBox also triggers a "PreviewKeyDown" event and pressing enter selects the first item in the result set, with up and down arrow keys traversing the results. The SelectedItem is bound to the DataContext for a GroupBox. This part works really nicely.

When an item is selected in the ComboBox, WPF is automatically attempting to replace "Text" with my SelectedItem. This causes my results set to get emptied and "Text" to revert to an empty string.

The behaviour I'd like is that when an item is selected, the text in the ComboBox remains exactly the same, so that my user can continue to traverse the result set using up and down arrows.

Is there an elegant way to achieve this? I think that nothing will be added to the question with a code snippet, but happy to supply if wanted.

The behaviour I'd like is that when an item is selected, the text in the ComboBox remains exactly the same, so that my user can continue to traverse the result set using up and down arrows.

That's a requirement that's not built into the ComboBox control. If you want something like that, you'll have to build it yourself (and subclassing most likely won't help, you'll have to build most of a ComboBox from scratch for this).

In fact you shouldn't be binding the current item like that either, you should use the SelectedItem property, which doesn't do any conversions or copying, exactly what you want for an internal binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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