C# 覆盖ListBox的输入绑定

C# 覆盖ListBox的输入绑定,c#,wpf,C#,Wpf,在我的主窗口中,我有一个列表框。当用户在我的窗口中按up/down/del时,我定义了cal命令。InputBindings 如何编写列表框以使用命令而不使用默认命令 <Window ...> <Window.InputBindings> <KeyBinding Command="{Binding UndoCommand}" Key="Z" Modifiers="

在我的主窗口中,我有一个列表框。当用户在我的
窗口中按up/down/del时,我定义了cal命令。InputBindings

如何编写列表框以使用命令而不使用默认命令

<Window ...>
    <Window.InputBindings>
        <KeyBinding Command="{Binding UndoCommand}"
                    Key="Z"
                    Modifiers="Ctrl"/>
        <KeyBinding Command="{Binding PrevItemCommand}"
                    Key="Up"/>
        <KeyBinding Command="{Binding NextItemCommand}"
                    Key="Down"/>
        <KeyBinding Command="{Binding RemoveCommand}"
                    Key="Delete"/>
    </Window.InputBindings>
    <Grid>
        <ListBox Grid.Row="0" 
                 Grid.Column="0"
                 x:Name="listRes"
                 Style="{StaticResource StyleListBox}"
                 ItemsSource="{Binding Results}"
                 SelectedItem="{Binding SelectedItem}"/>
    </Grid>
</Window>
A在函数
OnNextItem
onpreviitem
上添加了断点

  • 单击列表框中的某个项目后(列表框获得焦点),上/下键会更改所选项目,但代码不会中断(不会调用我的函数)
  • 单击“我的窗口”中的复选框(列表框失去焦点)后,向上/向下键代码中断(调用我的函数)

尝试将键绑定移动到列表框本身:

<ListBox Grid.Row="0" 
                 Grid.Column="0"
                 x:Name="listRes"
                 Style="{StaticResource StyleListBox}"
                 ItemsSource="{Binding Results}"
                 SelectedItem="{Binding SelectedItem}">
    <ListBox.InputBindings>
        <KeyBinding Command="{Binding UndoCommand}" Key="Z" Modifiers="Ctrl"/>
        <KeyBinding Command="{Binding PrevItemCommand}" Key="Up"/>
        <KeyBinding Command="{Binding NextItemCommand}" Key="Down"/>
        <KeyBinding Command="{Binding RemoveCommand}" Key="Delete"/>
    </ListBox.InputBindings>
</ListBox>


“当我在点击一个项目后使用向上/向下键时,它们不会到达。如果我在点击另一个项目后使用向上/向下键,它们就会到达。”这是什么意思。。。?你能详细解释一下你的问题吗?@mm8我编辑了我的问题,很有效,谢谢。但有一种方法可以做到这一点,而无需编写两次代码?(在窗口和列表框上)您不能从中删除键绑定吗?否则,您需要编写两次相同的标记,即,您需要将4个键绑定添加到列表框,将另外4个键绑定添加到父窗口。我无法从
中删除,我希望在焦点位于其他项目时调用该命令。我将编写代码2次,并添加注释以供记住。非常感谢。
<ListBox Grid.Row="0" 
                 Grid.Column="0"
                 x:Name="listRes"
                 Style="{StaticResource StyleListBox}"
                 ItemsSource="{Binding Results}"
                 SelectedItem="{Binding SelectedItem}">
    <ListBox.InputBindings>
        <KeyBinding Command="{Binding UndoCommand}" Key="Z" Modifiers="Ctrl"/>
        <KeyBinding Command="{Binding PrevItemCommand}" Key="Up"/>
        <KeyBinding Command="{Binding NextItemCommand}" Key="Down"/>
        <KeyBinding Command="{Binding RemoveCommand}" Key="Delete"/>
    </ListBox.InputBindings>
</ListBox>