WPF TreeView KeyBinding Ctrl + Down

时间:2018-05-10 18:27:39

标签: wpf treeview keyboard-shortcuts

我尝试在树视图中将Ctrl + Down作为自定义快捷键处理。我尝试过以下代码:

<Window x:Class="WpfTreeIssue.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfTreeIssue"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800"
    x:Name="_this">
<Grid DataContext="{Binding ElementName=_this}">
    <TreeView>
        <TreeView.InputBindings>
            <KeyBinding
                Key="Down" Modifiers="Ctrl"
                Command="{Binding ControlDownCommand}" />
            <KeyBinding
                Key="A"
                Command="{Binding ControlDownCommand}" />
        </TreeView.InputBindings>

        <TreeViewItem Header="Level 1" IsExpanded="True">
            <TreeViewItem Header="Level 2.1" />
            <TreeViewItem Header="Level 2.2" IsExpanded="True">
                <TreeViewItem Header="Level 3.1" />
                <TreeViewItem Header="Level 3.2" />
            </TreeViewItem>
            <TreeViewItem Header="Level 2.3" />
        </TreeViewItem>
    </TreeView>
</Grid>

代码隐藏:

public partial class MainWindow : Window
{
    public ICommand ControlDownCommand
    {
        get
        {
            return new RelayCommand<KeyBinding>(x => OnControlDown(x));
        }
    }

    private void OnControlDown(KeyBinding keyBinding)
    {
        Console.Write("HELLO");
    }

    public MainWindow()
    {
        InitializeComponent();
    }
}

RelayCommand是一个基本的ReplayCommand,如下所示:https://www.c-sharpcorner.com/UploadFile/20c06b/icommand-and-relaycommand-in-wpf/

我已为Ctrl-Down和&amp;添加了KeyBindings。 A。 <{1}}快捷方式可以正常工作,但Ctrl-Down不起作用。

我尝试删除Ctrl修饰符并且向下快捷方式仍无效(它会移动所选的树项,这很有意义)。有趣的是,如果您导航到树视图中的最后一个项目并按下(Ctrl-down在该实例中不起作用),则向下快捷方式可以工作。

关于如何让Ctrl-Down KeyBinding在我的TreeView上工作的任何建议?

编辑:我还尝试重写TreeView的OnKeyDown和OnPreviewKeyDown方法而没有运气。见下文:

A

如果我按住Ctrl键&amp;按下public class CustomTreeView : TreeView { protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.Down) { Console.WriteLine("Down arrow"); if ((e.KeyboardDevice.IsKeyDown(Key.RightCtrl) || e.KeyboardDevice.IsKeyDown(Key.LeftCtrl))) { Console.WriteLine("TEST"); e.Handled = true; } } base.OnKeyDown(e); } protected override void OnPreviewKeyDown(KeyEventArgs e) { if (e.Key == Key.Down) { Console.WriteLine("Down arrow"); if ((e.KeyboardDevice.IsKeyDown(Key.RightCtrl) || e.KeyboardDevice.IsKeyDown(Key.LeftCtrl))) { Console.WriteLine("TEST"); e.Handled = true; } } base.OnPreviewKeyDown(e); } } 行永不被击中(未发送向下箭头事件)。如果我只是按下,则会触发该行,但未设置ctrl修饰符。

0 个答案:

没有答案