2013-04-30 20 views
0

如何讓我的可編輯組合框同時接受和保留用戶輸入,同時動態更新組合框中可用的選項?WPF可編輯組合框 - 在更新可觀察列表時保留輸入

我想要完成的是允許用戶開始輸入查詢,並根據迄今輸入的內容顯示查詢建議。獲得建議並更新comobobox的內容會很順利,但在每次更新時,輸入都將被清除,並替換爲更新列表中的第一個條目。

這是我到目前爲止已經試過

<ComboBox x:Name="cmboSearchField" Margin="197,10,0,0" 
VerticalAlignment="Top" Width="310" IsTextSearchEnabled="True" 
IsEditable="True" ItemsSource="{Binding SearchTopics}" 
KeyUp="GetSearchTopics"/> 

背後我的代碼(與其它相似的,所以建議,並沒有十分地成功一起):

public ObservableCollection<string> SearchTopics {get;set;} 

void GetSearchTopics(object sender, KeyEventArgs e) 
{ 
    bool showDropdown = this.cmboSearchField.IsDropDownOpen; 

    if ((e.Key >= Key.D0) && (e.Key <= Key.Z)) 
    { 
     query = this.cmboSearchField.Text; 

     List<string> topics = GetQueryRecommendations(query); 

     _searchTopics.Clear(); 

     _searchTopics.Add(query); //add the query back to the top 

     //stuffing the list into a new ObservableCollection always 
     //rendered empty when the dropdown was open   
     foreach (string topic in topics) 
     { 
     _searchTopics.Add(topic); 
     } 

     this.cmboSearchField.SelectedItem = query; //set the query as the current selected item 

     //this.cmboSearchField.Text = query; //this didn't work either 

     showDropdown = true; 
    } 


    this.cmboSearchField.IsDropDownOpen = showDropdown; 
} 

回答

0

事實證明,更新ObservableCollection與我看到的行爲沒有任何關係。後來我意識到,它的行爲好像打字是在搜索下拉集合中的匹配條目,從而替換用戶每次提供的任何輸入。

那正是發生的情況。在窗口XAML中將ComboBox元素的IsTexSearchEnabled屬性設置爲false解決了該問題。

<ComboBox x:Name="cmboSearchField" Margin="218,10,43,0" 
IsTextSearchEnabled="false" VerticalAlignment="Top" 
IsEditable="True" ItemsSource="{Binding SearchTopics}" 
KeyUp="GetSearchTopics"/> 
0

你不應該清除可觀察的集合。

如果清除集合,那麼在某些時候列表是空的,並且對selecteditem的引用將丟失。

相反,只要看看哪些項目已經在那裏,只添加那些尚不可用的項目。

+0

恐怕我仍然看到的行爲不同意。即使我沒有清除集合,SelectedItem也被覆蓋;從而破壞用戶輸入的內容。 – BrMcMullin 2013-04-30 21:35:22