打開 ComboBox DropDown 時不要選擇文本輸入 (Do not select text input when ComboBox DropDown is opened)


問題描述

打開 ComboBox DropDown 時不要選擇文本輸入 (Do not select text input when ComboBox DropDown is opened)

我的 WPF 應用程序中有一個 ComboBox,我想在其中輸入文本,用於更新 ComboBox 的內容(項目)。

每當我輸入一個字符時,我都想要更新了要顯示的項目。所以我設置了 IsDropDownOpen = true;,但這會導致輸入的 Text 被選中。

結果是:我輸入 1 個字符,ComboBox DropDown 被打開(並且顯示新項目),字符被選中。我鍵入第二個字符並替換第一個字符,因為它已被選中(duh)!

如何取消選擇組合框中的所有文本?我顯然想輸入超過 1 個字符,而不必再次單擊 ComboBox 以取消選擇所有文本...

代碼:

//MainWindow.xaml
<ComboBox x:Name="comboBoxItemID" HorizontalAlignment="Left" Height="38"
 VerticalAlignment="Top" Width="300" Canvas.Left="197" FontSize="21.333"
 IsEnabled="True" KeyUp="comboBoxItemID_KeyUp" IsEditable="True"/>

//comboBoxItemID_KeyUp()
List<InventorySearchResult> Items = Invent.SearchArticle(this.comboBoxItemID.Text); //Get new Data
comboBoxItemID.ItemsSource = Items;         //Update comboBox Data
comboBoxItemID.DisplayMemberPath = "Name";
comboBoxItemID.IsDropDownOpen = true;

參考解法

方法 1:

To deselect all Text from a ComboBox, first get the TextBox Element:

TextBox tb = (TextBox)comboBoxItemID.Template.FindName("PART_EditableTextBox", comboBoxItemID);

(source: How to get ComboBox.SelectedText in WPF )

Then use the TextBox method Select(int start, int length) to set the selection, e.g.

tb.Select(tb.Text.Length, 0);

(source: Deselect text in a textbox )

Finally, disable the IsTextSearchEnabled property. I haven't done much testing to find out why exactly this has to be disabled, but I guess in my case it conflicts with the way I update the Items and then deselect the Text.

(by NoMadNoMad)

參考文件

  1. Do not select text input when ComboBox DropDown is opened (CC BY‑SA 2.5/3.0/4.0)

#Combobox #wpf #C#






相關問題

tcl/tk 小部件組合框失去焦點 (tcl/tk widget combobox loses focus)

Flex Combobox 奇怪的問題 (Flex Combobox strange problem)

在組合框中對齊文本 (Align Text in Combobox)

如何同時綁定到 ComboBox 中的兩個不同的依賴屬性? (How do I bind to two different dependency properties in a ComboBox at the same time?)

在綁定到字典的組合框中設置所選項目 (Setting selected item in combobox bound to dictionary)

easyUI datagrid內部編輯組合框無法選擇默認值 (easyUI datagrid inner edit combobox cannot selected default value)

VBA:數據輸入組合框有效,但命令按鈕給出“無效的屬性值”錯誤 (VBA: Data entry into combobox works, but command button gives "Invalid property value" error)

vb.net - 組合框總是選擇第一個值 (vb.net - combo box always select the first value)

打開 ComboBox DropDown 時不要選擇文本輸入 (Do not select text input when ComboBox DropDown is opened)

如何使用相同的數據源設置多個組合框? (How can I set up multiple combo-boxes with the same data source?)

如何使用 QtreeView 在 QComboBox 中設置所選項目 (How to set selected item in QComboBox with QtreeView)

Tkinter 組合框 Python (Tkinter Combobox Python)







留言討論