2014-04-11 106 views
1

我有一個ComboBoxDataSource屬性設置爲這個Type的列表:組合框的DropDownList搜索文本

public class ListInfo 
{ 
    public int Key { get; set; } 
    public string Name { get; set; } 
} 

DropDownStyle設置爲DropDownList,我設置了AutoCompleteSourceListItemsAutoCompleteModeSuggestAppend

經過一些測試後,客戶端回來並要求能夠找到文本值的任何部分,而不僅僅是從文本的開頭。我看到的大多數示例都是在DropDownStyle設置爲DropDown時執行此操作的,我無法這樣做,因爲用戶無法編輯列表中的內容,只需選擇一個值即可。

我試圖創建一個CustomSource,但是當我嘗試將AutoCompleteMode設置爲任意值,我得到了以下信息:可用於

只值AutoCompleteMode.None當DropDownStyle是 ComboBoxStyle。 DropDownList和AutoCompleteSource不是 AutoCompleteSource.ListItems。

我找到了這個AutoSuggestCombo,但我又碰到了問題DropDownStyle

如何,我不是:

  1. 使用ComboBoxDropDownStyle設置爲DropDown,不允許最終用戶進入新的元素?

  2. 能夠搜索ItemsString價值的任何部分,而不僅僅是當前的DropDownList風格使用的StartsWith

這是開始使用的Rx的機會,或者是路線臃腫的解決方案和隨之而來的學習曲線? (到目前爲止使用簡單教程)

回答

2

您必須將所有Autocompletion屬性設置爲none並自行處理這些內容。 可能有更簡單的解決方案,但您可以像這樣編寫KeyPress事件。

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    SortedDictionary<int, ListInfo> dict = new SortedDictionary<int, ListInfo>(); 

    int found = -1; 
    int current = comboBox1.SelectedIndex; 

    // collect all items that match: 
    for (int i = 0; i < comboBox1.Items.Count; i++) 
     if (((ListInfo)comboBox1.Items[i]).Name.ToLower().IndexOf(e.KeyChar.ToString().ToLower()) >= 0) 
     // case sensitive version: 
     // if (((ListInfo)comboBox1.Items[i]).Name.IndexOf(e.KeyChar.ToString()) >= 0) 
       dict.Add(i, (ListInfo)comboBox1.Items[i]); 

    // find the one after the current position: 
    foreach (KeyValuePair<int, ListInfo> kv in dict) 
      if (kv.Key > current) { found = kv.Key; break; } 

    // or take the first one: 
    if (dict.Keys.Count > 0 && found < 0) found = dict.Keys.First(); 

    if (found >= 0) comboBox1.SelectedIndex = found; 

    e.Handled = true; 

} 

您可以決定是否需要區分大小寫;可能不是..