Я пытаюсь реализовать предложения ComboBox, например Google:
![](https://i.stack.imgur.com/eiEbD.png)
Пользователь вводит несколько символов и появляется список с предложениями.
Итак, у меня есть следующий код:
<!--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;
}
}
Лямбда, описанная в конструкторе, вызывается при загрузке предложений.
У меня есть следующие проблемы с этим кодом. Во-первых, я не могу обработать Key.Down (txtMain_PreviewKeyDown не вызывается при нажатии). Поэтому для выбора предложения из списка пользователю необходимо использовать мышь. Во-вторых, когда некоторые предложения были найдены и список был удален, текст в ComboBox становится выделенным (синим), что не то, что я хочу (я не хочу, чтобы текст был выбран, когда предложение было выбрано):
![](https://i.stack.imgur.com/E4a3p.png)