我正在尝试实施像Google一样的建议ComboBox:
用户输入多个符号,并显示包含建议的列表。 所以我有以下代码:
<!--Search query textBox-->
<ComboBox x:Name="txtMain" IsEditable="True" TextBoxBase.SelectionChanged="txtMain_SelectionChanged"
TextBoxBase.TextChanged=" txtMain_TextChanged"
KeyDown="txtMain_PreviewKeyDown"
SelectionChanged=" txtMain_SelectionChanged" IsTextSearchEnabled="False" />
public SearchControl()
{
InitializeComponent();
_search = new SearchViewModel(doc);
_suggestionCom = new SuggestionsCommand(
(object s, RunWorkerCompletedEventArgs evarg) =>
{
List<string> results = _suggestionCom.Suggestions;
if (results != null && results.Count() > 0)
{
txtMain.ItemsSource = results;
}
else
{
txtMain.ItemsSource = null;
}
txtMain.IsDropDownOpen = true;
});
}
void autoTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
if (_prevText.Equals(txtMain.Text))
return;
// Only autocomplete when there is text
if (txtMain.Text.Length > 0)
{
string lastInput = txtMain.Text;
_prevText = lastInput;
_suggestionCom.Execute(lastInput); //it starts a new thread which download suggestions from the service
}
else
{
txtMain.ItemsSource = null;
}
}
catch (Exception err)
{
}
}
void txtMain_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Down)
{
if (txtMain.SelectedIndex < txtMain.Items.Count)
{
txtMain.SelectedIndex = txtMain.SelectedIndex + 1;
}
}
if (e.Key == Key.Up)
{
if (txtMain.SelectedIndex > -1)
{
txtMain.SelectedIndex = txtMain.SelectedIndex - 1;
}
}
if (e.Key == Key.Enter)
{
// Commit the selection
//txtMain.Visibility = Visibility.Collapsed;
e.Handled = (e.Key == Key.Enter);
//Perform search here
}
if (e.Key == Key.Escape)
{
// Cancel the selection
txtMain.ItemsSource = null;
//suggestionListBox.Visibility = Visibility.Collapsed;
}
}
在下载建议时调用构造函数中描述的Lambda。 我对此代码有以下问题。首先,我无法处理Key.Down(按下时不调用txtMain_PreviewKeyDown)。因此,为了从列表中选择建议用户需要使用鼠标。其次,当找到一些建议并删除列表时,ComboBox中的文本将被选中(蓝色),这不是我想要的(我不希望在选择建议时选择文本):
答案 0 :(得分:1)
AutoCompleteBox更适合处理这种行为。
答案 1 :(得分:1)
对于一个,在这种情况下,你应该在你的xaml中使用“PreviewKeyDown”而不是“KeyDown”,因为你想要一个隧道事件。那么,您可能必须覆盖“焦点”方法才能删除文本上的选择。
但就我而言,我会选择一个附属财产,如另一个问题的回答所述:
Is this the best way to build AutoSuggest into a WPF ComboBox?
您可能还想使用autoComplete TextBox而不是comboBox:
http://www.codeproject.com/KB/WPF/WPFAutoCompleteTextbox.aspx
和
http://www.lazarciuc.ro/ioan/2008/06/01/auto-complete-for-textboxes-in-wpf/
(我不喜欢重新发明轮子;-))