Reputation: 5211
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 combobox.
<ComboBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120"
PreviewKeyDown="comboBox1_PreviewKeyDown" KeyDown="comboBox1_KeyDown" IsEditable="True"/>
C#
private void comboBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Down)
MessageBox.Show("hi");
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Down)
MessageBox.Show("hi");
}
The event is not even hit when i press down arrow key.
Upvotes: 3
Views: 4141
Reputation: 61
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)
{
}
}
Upvotes: 2
Reputation: 496
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);
}
}
Upvotes: 0
Reputation: 10823
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)?
Upvotes: 2