覆盖ListBox

时间:2017-01-31 15:52:53

标签: c# wpf

在我的MainWindows中,我有一个ListBox。当用户在我的Window.InputBindings按下向上/向下/ del时,我将命令定义为cal。

如何编写ListBox以使用我的命令而没有默认命令?

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

我在命令中添加了断点,在点击项目后使用上/下时未达到断点。如果我在点击其他项目后使用上/下,则会触及它们。

编辑(解释最后一句):

private ICommand _previtemCommand;
public ICommand PrevItemCommand
{
    get
    {
        if (_previtemCommand == null)
            _previtemCommand = new RelayCommand(OnPrevItem);
        return _previtemCommand;
    }
}
private void OnPrevItem()
{
    // Do something
}

private ICommand _nextitemCommand;
public ICommand NextItemCommand
{
    get
    {
        if (_nextitemCommand == null)
            _nextitemCommand = new RelayCommand(OnNextItem);
        return _nextitemCommand;
    }
}
private void OnNextItem()
{
    // Do something
}

在函数OnNextItemOnPrevItem上添加了断点。

  • 单击ListBox中的项目(ListBox获得焦点)后,向上/向下键更改所选项目但代码不会中断(我的函数未被调用)
  • 点击我的窗口中的支票(ListBox丢失了焦点),上下键代码中断(我的函数被调用)

1 个答案:

答案 0 :(得分:1)

尝试将KeyBindings移动到ListBox本身:

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