Reputation: 3295
In my MainWindows, I have a ListBox. I defined commands to cal when user press up/down/del in my Window.InputBindings
.
How can I write my ListBox to use my commands and no default command ?
<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>
I added breakpoints in my commands, they are not reached when I use up/down after clicking on an item. They are reached if I use up/down after clicking on an other item.
Edit (explain last sentence):
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
}
A added breakpoints on functions OnNextItem
and OnPrevItem
.
Upvotes: 0
Views: 515
Reputation: 169360
Try to move the KeyBindings to the ListBox itself:
<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>
Upvotes: 1