Hi,
I have implemented a Autocomplete enabled Combobox in WPF. It is like below...
private void cbxSession_Loaded(object sender, RoutedEventArgs e)
{
cbxSession.ApplyTemplate();
TextBox textBox = cbxSession.Template.FindName("PART_EditableTextBox", cbxSession) as TextBox;
textBox.IsReadOnly = false;
if (textBox != null)
{
textBox.KeyUp += new KeyEventHandler(textBox_KeyUp);
textBox.KeyUp += delegate
{
///open the drop down and start filtering based on what the user types into the combobox
cbxSession.IsDropDownOpen = true;
cbxSession.Items.Filter += a =>
{
if (a.ToString().ToUpper().Contains(textBox.Text.ToUpper()))
return true;
else
return false;
};
};
}
}
void textBox_KeyUp(object sender, KeyEventArgs e)
{
if ((e.Key == System.Windows.Input.Key.Up) || (e.Key == System.Windows.Input.Key.Down))
{
e.Handled = true;
}
else if (e.Key == System.Windows.Input.Key.Enter)
{
e.Handled = true;
cbxSession.IsDropDownOpen = false;
}
}
void textBox_KeyDown(object sender, KeyEventArgs e)
{
cbxSession.SelectionChanged -= cbxSession_SelectionChanged;
if (e.Key == System.Windows.Input.Key.Enter)
{
e.Handled = true;
cbxSession.SelectionChanged += cbxSession_SelectionChanged;
}
if ((e.Key == System.Windows.Input.Key.Up) || (e.Key == System.Windows.Input.Key.Down))
{
e.Handled = true;
}
}
private void cbxSession_DropDownClosed(object sender, EventArgs e)
{
if (cbxSession.Text != "")
{
TextBox textBox = cbxSession.Template.FindName("PART_EditableTextBox", cbxSession) as TextBox;
if (!cbxSession.Items.Contains(textBox.Text))
{
textBox.Text = cbxSession.Text;
}
}
}
private void cbxSession_DropDownOpened(object sender, EventArgs e)
{
cbxSession.Items.Filter += a =>
{
return true;
};
}
<ComboBox x:Name="cbxSession" Width="260" Canvas.Top="5" Canvas.Left="79" Height="25" Visibility="Visible" SelectionChanged="cbxSession_SelectionChanged" MaxDropDownHeight="200" IsTextSearchEnabled="False" IsEditable="True" IsReadOnly="True" Loaded="cbxSession_Loaded" DropDownClosed="cbxSession_DropDownClosed" StaysOpenOnEdit="True" DropDownOpened="cbxSession_DropDownOpened">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel IsVirtualizing="True" IsItemsHost="True"/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
But, the problem I am facing is... When I try searching, the first character goes missing.
And this happens only once.
Secondly, When I am using Arrow buttons to the filtered items, the ComboboxSelectionChanged event is fired. Is there any way to make it fire only on the click of 'Enter'