开发者

WPF: ApplicationCommands seem to ignore CommandTarget

开发者 https://www.devze.com 2023-03-21 12:42 出处:网络
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:

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:

WPF: ApplicationCommands seem to ignore CommandTarget

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>开发者_Go百科;
            <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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号