问题
I am trying to capture the down and up keys (the direction rows) but when I press this keys, it is not raised the event keydown.
However, if I press any other key, the event is raised. For example numlock is catched. The row keys are special keys?
I am using MVVMLight to convert the events to command, and pass the KeyEventArgs.
Thanks.
EDIT: add some code
Well. really I have a comboBox, and is editable, so I can write text inside the comboBox. How the search option is enabled, while I am writing, the selecition is changed.
So the selection can change for many reasons: I write and the comboBox change the selection because of the search option, I can change the selection with the mouse and I can change the selection with the arrow keys.
I would like to know which is the reason of the selection change. So I need to know when in my comboBox I press down or up arrow keys.
I have this code:
AXML
<ComboBox DisplayMemberPath="Type" Height="23" HorizontalAlignment="Left" IsSynchronizedWithCurrentItem="True" Margin="0,16,0,0" Name="cmbType" VerticalAlignment="Top" Width="238"
ItemsSource="{Binding Path=Types}"
SelectedIndex="{Binding Path=TypesIndex}" IsEditable="True"
Text="{Binding TypesText}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewKeyDown">
<cmd:EventToCommand Command="{Binding TypesPreviewKeyDownCommand, Mode=OneWay}" PassEventArgsToCommand="True" />
</i:EventTrigger>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand Command="{Binding TypesSelectionChangedCommand, Mode=OneWay}" CommandParameter="{Binding ElementName=cmbTypes, Path=SelectedItems}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
In my viewModel:
private RelayCommand<KeyEventArgs> _typesPreviewKeyDownCommand = null;
public RelayCommand<KeyEventArgs> typesPreviewKeyDownCommand
{
get
{
if (_typesPreviewKeyDownCommand == null)
{
_typesPreviewKeyDownCommand = new RelayCommand<KeyEventArgs>(typesPreviewKeyDownCommand);
}
return _typesPreviewKeyDownCommand;
}
}
private void typesPreviewKeyDownCommand(KeyEventArgs e)
{
if (e.Key == Key.Down || e.Key == Key.Up)
{
//my code
}
else
{
//more code
}
}
回答1:
Not sure if relevant anymore, but here's an article on CodeProject which discusses a very similar issue/behaviour Up/Down behavior on a DatePicker
It's very simple to handle in the Code Behind like the article suggests, but if you want to do it MVVM style, you need to go with the i:Interaction
or InputBindings
.
I prefer the Interaction, since coupled with mvvm-light it seems to work better for me, while with the InputBindings
I've found that up/down keys didn't work, while having a modifier like ALT would work.
As the comments said, it's probably being handled somewhere on the way before it gets to you. (this is why you'd like to use the PreviewKeyDown
and not KeyDown
).
来源:https://stackoverflow.com/questions/12114774/keydown-event-how-to-capture-down-and-up-key-rows