WPF 树视图键绑定 Ctrl + 向下



我正在尝试将树视图中的 Ctrl + 向下作为自定义快捷方式处理。我尝试了以下代码:

<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();
}
}

中继命令是一个基本的重放命令,如下所示:https://www.c-sharpcorner.com/UploadFile/20c06b/icommand-and-relaycommand-in-wpf/

我已经为Ctrl-DownA添加了KeyBindings。A快捷方式工作正常,但 Ctrl-Down 不起作用。

我尝试删除 Ctrl 修饰符,但向下快捷方式仍然不起作用(它会移动选定的树项,这是有意义的(。有趣的是,如果您导航到树视图中的最后一个项目并按下,向下快捷方式确实有效(Ctrl-down 在这种情况下不起作用(。

关于如何让 Ctrl-Down 键绑定在我的树视图上工作的任何建议?

编辑:我也尝试覆盖TreeView的OnKeyDown和OnPreviewKeyDown方法,但没有运气。见下文:

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 键并按下该行Console.WriteLine("Down arrow");永远不会被击中(不会发送向下箭头事件(。如果我只是按下,该行会被击中,但未设置 ctrl 修饰符。

TreeView控件中有一个代码,用于处理 Ctrl+Down,因此绑定不起作用,因为 keys 事件已处理。您需要覆盖TreeView上的OnKeyDown才能执行自己的操作。

更新:这是一个经过测试的示例

protected override void OnKeyDown(KeyEventArgs e)
{
if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
if (System.Windows.Input.Key.Down == e.Key)
{
System.Diagnostics.Trace.WriteLine("Ctlr+Down");
e.Handled = true;
}
}
if (!e.Handled)
{
base.OnKeyDown(e);
}
}

最新更新