在我的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
}
在函数OnNextItem
和OnPrevItem
上添加了断点。
答案 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>