I have a combobox on a window in wpf and i am trying to capture the down arrow key of this combobox but i am not able to do so. The following is the only code i have for the com
Create a new Combo box class by inheriting from the base ComboBox. Below code explains how to. You may come across such problems when you add combo box to another control like Data grid cell. Hope this helps!
http://csharpquestsolution.blogspot.com/2013/11/arrow-key-events-not-getting-fired-on.html
public class MyComboBox : ComboBox
{
protected override bool ProcessKeyMessage(ref Message m)
{
KeyEventArgs keyArgs = new KeyEventArgs((Keys)m.WParam);
switch(keyArgs.KeyCode)
{
case Keys.Up :
//Implement your code here.
return true;
case Keys.Down :
//Implement your code here.
return true;
}
return base.ProcessKeyMessage(ref m);
}
}
This code is helpful for me.
<StackPanel PreviewKeyDown="StackPanel_PreviewKeyDown">
<ComboBox>
<ComboBoxItem>item1</ComboBoxItem>
<ComboBoxItem>item2</ComboBoxItem>
<ComboBoxItem>item3</ComboBoxItem>
</ComboBox>
</StackPanel>
CodeBehind
private void StackPanel_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Down)
{
}
}
Try handling PreviewKeyUp (or KeyUp) instead. If that does not work, then there must be more to your window or code (are you handling other instances of these events)?