2015-06-10 211 views
1

我在wpf控件中可編輯組合框。可編輯Combobox被凍結後編輯

<ComboBox Width="200" Name="quickSearchText" 
    TextBoxBase.TextChanged="searchTextChanged" 
    IsTextSearchEnabled="False" 
    StaysOpenOnEdit="True" IsEditable="True"> 
</ComboBox> 

文本輸入後我改變組合框項目(如自動完成文本框)。

private void searchTextChanged(object sender, TextChangedEventArgs e) 
{ 
    string text = quickSearchText.Text; //Get typing text. 
    List<string> autoList = new List<string>(); 

    autoList.AddRange(suggestions.Where(suggestion => !string.IsNullOrEmpty(text)&& suggestion.StartsWith(text))); //Get possible suggestions. 

    // Show all, if text is empty. 
    if (string.IsNullOrEmpty(text) && autoList.Count == 0) 
    { 
     autoList.AddRange(suggestions); 
    } 

    quickSearchText.ItemsSource = autoList; 
    quickSearchText.IsDropDownOpen = autoList.Count != 0; //Open if any. 
} 

如果我選擇從下拉菜單或輸入文本的項目,然後按Enter的TextboxBase僵住了,我不能編輯它。 (但可以突出顯示文字並打開/關閉下拉菜單)

如何解決?

+0

你可以用'TextBox'控制&用Combobox控制Popup。在TextBox的'TextChanged'事件上,你可以顯示/隱藏'Popup'。 –

+0

@Amol Bavannavar謝謝。它是解決方案之一。但爲什麼當前的解決方案不起作用? –

回答

2

當前的解決方案沒有因爲這條線的工作:

quickSearchText.ItemsSource = autoList; 

這將重置您的ComboBox數據,因此在輸入文本所做的每個更改將丟失。

您的解決方案工作,你應該使用數據,如下面結合

背後代碼:

public MainWindow() 
{ 
    InitializeComponent(); 
    DataContext = this; 
    autoList = new ObservableCollection<string>(); 
} 

private List<string> suggestions; 
public ObservableCollection<string> autoList { get; set; } 
private void searchTextChanged(object sender, TextChangedEventArgs e) 
{ 
    string text = quickSearchText.Text; //Get typing text. 

    var suggestedList = suggestions.Where(suggestion => !string.IsNullOrEmpty(text) && suggestion.StartsWith(text)); //Get possible suggestions 
    autoList.Clear(); 

    foreach (var item in suggestedList) 
    { 
     autoList.Add(item); 
    } 

    // Show all, if text is empty. 
    if (string.IsNullOrEmpty(text) && autoList.Count == 0) 
    { 
     foreach (var item in suggestions) 
     { 
      autoList.Add(item); 
     } 
    } 

    quickSearchText.IsDropDownOpen = autoList.Count != 0; //Open if any. 
} 

的XAML:

<ComboBox Width="200" Name="quickSearchText" 
      ItemsSource="{Binding autoList}" 
      TextBoxBase.TextChanged="searchTextChanged" 
      IsTextSearchEnabled="False" 
      StaysOpenOnEdit="True" IsEditable="True"> 
</ComboBox> 
+0

使用ObservableCollection幫助了我,但綁定的數據沒有在視圖上更新,所以我仍然需要通過代碼重置ItemsSource。 –

1

在穿戴:

quickSearchText.ItemsSource = null; 

如searchTextChanged函數的第一行。似乎不清除ItemsSource事先導致奇怪的行爲,並把這條線首先似乎修復它。