Jan
Jan

Reputation: 693

WPF: ApplicationCommands seem to ignore CommandTarget

I have a TextBox and a ListView in my window, and I'd like to move the ListView's selection up and down while the TextBox has focus:

enter image description here

However, I don't seem to get my CommandTarget declarations across, they're ignored. MSDN says this is default behavior for non-RoutedCommands, but the movement commands I try to use are RoutedUICommands, so this is probably not the problem here.

Am I missing something?

My XAML currently looks like this (code behind is empty):

<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Test Window">
    <StackPanel>
        <TextBox>
            <TextBox.InputBindings>
                <!-- for some reason, these two won't work -->
                <KeyBinding Key="Down" 
                            Command="ComponentCommands.MoveDown"
                            CommandTarget="{Binding ElementName=AllItemsList}"/>
                <KeyBinding Key="Up" 
                            Command="ComponentCommands.MoveUp"
                            CommandTarget="{Binding ElementName=AllItemsList}"/>
            </TextBox.InputBindings>
        </TextBox>
    <ListView x:Name="AllItemsList">
            <ListViewItem>Item 1</ListViewItem>
            <ListViewItem>Item 2</ListViewItem>
            <ListViewItem>Item 3</ListViewItem>
        </ListView>
    </StackPanel>
</Window>

Upvotes: 2

Views: 624

Answers (1)

Ed Bayiates
Ed Bayiates

Reputation: 11230

Actually since RoutedUICommand derives from RoutedCommand, both of them support a command target (the MSDN actually says command targets ONLY work on RoutedCommands, but what it means is it doesn't work on other ICommand derived objects).

Have you actually bound the ComponentCommands mentioned (MoveDown and MoveUp) into the ListView in your code behind? ListView is empty of command bindings when first created, so you'd need to do something like:

AllItemsList.CommandBindings.Add(new CommandBinding(ComponentCommands.MoveDown, ExecuteMoveDown));

You would then have to write your ExecuteMoveDown function to do the moving.

Upvotes: 1

Related Questions