4

我正在尝试捕获向下和向上键(方向行)但是当我按下此键时,它不会引发事件 keydown。

但是,如果我按任何其他键,则会引发事件。例如 numlock 被捕获。行键是特殊键吗?

我正在使用 MVVMLight 将事件转换为命令,并传递 KeyEventArgs。

谢谢。

编辑:添加一些代码

出色地。我真的有一个组合框,并且是可编辑的,所以我可以在组合框内写文本。如何启用搜索选项,在我写作时,选择发生了变化。

所以选择可能会因多种原因而改变:我写了,comboBox 会因为搜索选项而改变选择,我可以用鼠标改变选择,也可以用箭头键改变选择。

我想知道选择更改的原因是什么。所以我需要知道我什么时候在我的组合框中按下或向上箭头键。

我有这个代码:

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>

在我的视图模型中:

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
            }
        }
4

1 回答 1

3

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).

于 2013-10-07T04:46:50.143 回答