Shuvro Pall

Shuvro Pall

  • NA
  • 134
  • 373.3k

Autocomplete Combobox in WPF

Jun 26 2012 7:40 AM
Guy's i am trying to autocomplete a combobox in WPF.But a problem stands there.When i type in combobox it's popup filters the items according to typed text nicely,but i need to select a option by mouse,cannot by keyboard arrow's.I tried to solve it with keydown event but somehow it cannot focus combobox i think.Someone can suggest me here what wrong i am doing or how can i enable keyboard arrowkey events?Below are my codes:

XML:
<ComboBox Height="23" HorizontalAlignment="Left" Margin="160,236,0,0"
Name="comboBox1" VerticalAlignment="Top" Width="120" IsEditable="True"
 ItemsSource="{Binding}" KeyDown="comboBox1_KeyDown">
  <ComboBox.Resources>
  <sys:Double x:Key="{x:StaticSystemParameters.VerticalScrollBarWidthKey}">0
  </sys:Double>
  </ComboBox.Resources>
</ComboBox>

C#:
public partial class MainWindow : Window
{
  List<string> nameList;
  public MainWindow()
  {
  InitializeComponent();
  nameList = new List<string> { "A0-Word","B0-Word","C0-Word",
  "A1-Word","A111","A11122","B1-Word",
  "C1-Word", "B2-Word","C2-Word", "C3-Word", }; 
        comboBox1.DataContext = nameList;  
  comboBox1.Loaded += delegate
  { 
            TextBox textBox =  comboBox1.Template.FindName("PART_EditableTextBox", comboBox1) as TextBox;

Popup popup = comboBox1.Template.FindName("PART_Popup", comboBox1) as Popup;

  if (textBox != null)
  {
  textBox.TextChanged += delegate { comboBox1.Items.Filter += (item) =>
  {
  if (item.ToString().StartsWith(textBox.Text))
  {
  popup.IsOpen = true;
  return true;
  }
  else {  return false; } };   }; } };  

 comboBox1.KeyDown+=new System.Windows.Input.KeyEventHandler(comboBox1_KeyDown);
 }  

private void comboBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{  
  if (e.Key == Key.Down)
  {
  e.Handled = true;
  comboBox1.Items.MoveCurrentToNext();
  }
 }