WPF TextBox 允许按键绑定撤消气泡

问题描述 投票:0回答:1

我通过允许键绑定事件冒泡到主窗口视图来处理应用程序中的键绑定,其中键绑定在 xaml 中定义并在主窗口视图模型中处理,例如,

 <Window.InputBindings>
    <KeyBinding Key="Left" Modifiers="Alt" Command="{Binding NavigateBackCommand}"/>
    <KeyBinding Key="Right" Modifiers="Alt" Command="{Binding NavigateForwardCommand}"/>
    <KeyBinding Key="c" Modifiers="Control" Command="{Binding CopyCommand}"/>
    <KeyBinding Key="v" Modifiers="Control" Command="{Binding PasteCommand}"/>
    <KeyBinding Key="d" Modifiers="Control" Command="{Binding DuplicateCommand}"/>
    <KeyBinding Key="n" Modifiers="Control" Command="{Binding AddCommand}"/>
    <KeyBinding Key="i" Modifiers="Control" Command="{Binding ImportCommand}"/>
    <KeyBinding Key="e" Modifiers="Control" Command="{Binding ExportCommand}"/>
    <KeyBinding Key="a" Modifiers="Control" Command="{Binding SelectAllCommand}"/>
    <KeyBinding Key="k" Modifiers="Control" Command="{Binding DeselectCommand}"/>
    <KeyBinding Key="z" Modifiers="Control" Command="{Binding UndoCommand}"/>
    <KeyBinding Key="y" Modifiers="Control" Command="{Binding RedoCommand}"/>
    <KeyBinding Key="z" Modifiers="Control+Shift" Command="{Binding RedoCommand}"/>
    <KeyBinding Key="F5" Command="{Binding RefreshCommand}"/>
    <KeyBinding Key="Delete" Command="{Binding DeleteCommand}"/>
    <KeyBinding Key="Escape" Command="{Binding EscapeCommand}"/>
</Window.InputBindings> 

除了

TextBox
控件外,此方法效果很好,其中撤消事件(“Ctrl+Z”)永远不会出现在主窗口中。我已经将
IsUndoEnabled
上的
TextBox
设置为 false,但它仍然没有出现气泡。就好像
TextBox
正在处理该事件,从而防止它一路冒泡。

我在自定义

TextBox
(
MyTextBox
) 中使用以下内容进行了修复,即监听控件中的
CommandBinding
,当点击时在窗口中查找
KeyBinding
并执行相关命令

public MyTextBox()
{
    IsUndoEnabled = false;

    CommandBindings.Add(new CommandBinding(
        ApplicationCommands.Undo,
        ((sender, args) =>
        {
            var window = Window.GetWindow(this);

            foreach (var keyBinding in window.InputBindings.OfType<KeyBinding>())
            {
                if (keyBinding.Key == Key.Y && keyBinding.Modifiers == ModifierKeys.Control)
                {
                    keyBinding.Command.Execute(null);
                }
            }
        })));
 }

但这看起来很老套。有没有办法禁用

TextBox
的内置撤消命令,而允许按键绑定冒泡,以便我可以处理它?

wpf textbox routed-commands
1个回答
0
投票

这几乎就好像 TextBox 正在处理该事件,从而防止它一直冒泡。

这正是它的作用。

有没有办法禁用文本框的内置撤消命令,而是允许键绑定冒泡,以便我可以处理它?

并非没有像您已经完成的那样实施某种“黑客”。在我看来,您创建自定义

TextBox
来处理此问题的解决方案实际上是一个很好的解决方案。

恐怕没有任何属性或类似属性可以让您设置来获得您想要的行为,即

TextBox
允许事件在没有任何自定义实现的情况下冒泡。

© www.soinside.com 2019 - 2024. All rights reserved.