gpt4 book ai didi

WPF 文本框拦截 RoutedUICommands

转载 作者:行者123 更新时间:2023-12-04 01:58:18 24 4
gpt4 key购买 nike

我正在尝试在我的 WPF 应用程序中使用 Undo/Redo 键盘快捷键(我使用 Command Pattern 实现了我自己的自定义功能)。然而,似乎 TextBox控件正在拦截我的“撤消”RoutedUICommand。

禁用此功能的最简单方法是什么,以便我可以在 UI 树的根部捕获 Ctrl+Z?我想避免在每个 TextBox 中添加大量代码/XAML如果可能的话,在我的申请中。

下面简要说明问题:

<Window x:Class="InputBindingSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:InputBindingSample"
Title="Window1" Height="300" Width="300">
<Window.CommandBindings>
<CommandBinding Command="loc:Window1.MyUndo" Executed="MyUndo_Executed" />
</Window.CommandBindings>
<DockPanel LastChildFill="True">
<StackPanel>
<Button Content="Ctrl+Z Works If Focus Is Here" />
<TextBox Text="Ctrl+Z Doesn't Work If Focus Is Here" />
</StackPanel>
</DockPanel>
</Window>
using System.Windows;
using System.Windows.Input;

namespace InputBindingSample
{
public partial class Window1
{
public static readonly RoutedUICommand MyUndo = new RoutedUICommand("MyUndo", "MyUndo", typeof(Window1),
new InputGestureCollection(new[] { new KeyGesture(Key.Z, ModifierKeys.Control) }));

public Window1() { InitializeComponent(); }

private void MyUndo_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("MyUndo!"); }
}
}

最佳答案

没有直接的方法来抑制所有绑定(bind),请勿设置 IsUndoEnabledfalse因为它只会捕获和刷新 Ctrl + Z 键绑定(bind)。您需要重定向 CanUndo , CanRedo , UndoRedo .这是我如何使用我的 UndoServiceActions单例。

textBox.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo,
UndoCommand, CanUndoCommand));
textBox.CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo,
RedoCommand, CanRedoCommand));

private void CanRedoCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = UndoServiceActions.obj.UndoService.CanRedo;
e.Handled = true;
}

private void CanUndoCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = UndoServiceActions.obj.UndoService.CanUndo;
e.Handled = true;
}

private void RedoCommand(object sender, ExecutedRoutedEventArgs e)
{
UndoServiceActions.obj.UndoService.Redo();
e.Handled = true;
}

private void UndoCommand(object sender, ExecutedRoutedEventArgs e)
{
UndoServiceActions.obj.UndoService.Undo();
e.Handled = true;
}

关于WPF 文本框拦截 RoutedUICommands,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1375483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com