简体   繁体   English

在 WPF、map 单击 MenuItem Edit->Undo to TextBox Ctrl-Z 键

[英]In WPF, map click of MenuItem Edit->Undo to TextBox Ctrl-Z key

Let's Say I'm making a simple editor in WPF using a TextBox and a Menu with the option "Edit->Undo".假设我正在 WPF 中使用文本框和带有“编辑->撤消”选项的菜单制作一个简单的编辑器。 My XML is as follows:我的 XML 如下:

<Window x:Class="WpfApp4.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:WpfApp4"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <DockPanel LastChildFill="True">
        <Menu Name="menu1" DockPanel.Dock="Top">
            <MenuItem Header="_Edit">
                <MenuItem Name="menu1_edit_undo"   
                          Header="_Undo"   
                          InputGestureText="Ctrl+Z"/>
            </MenuItem>
        </Menu>

        <Grid>
            <TextBox Name="textbox1"/>
        </Grid>
    </DockPanel>
    
</Window>

How do I get the Click event for "menu1_edit_undo" to send the Key Stroke "Ctrl-Z" to the TextBox component textbox1 to invoke the undo feature of the textbox?如何获取“menu1_edit_undo”的 Click 事件以将按键“Ctrl-Z”发送到 TextBox 组件 textbox1 以调用文本框的撤消功能?

HEre's what I tried that didn't work:这是我尝试过的但不起作用的方法:

        private void menu1_edit_undo_Click(
           object sender, RoutedEventArgs e)
        {
            var e2 = new KeyEventArgs(
                keyboard: Keyboard.PrimaryDevice,
                inputSource: PresentationSource.FromVisual(textbox1),
                timestamp: 0,
                key: Key.LeftCtrl | Key.Z
            )
            {
                RoutedEvent= Keyboard.KeyDownEvent 
            };

            textbox1.RaiseEvent(e2);
        }

The WPF TextBox has an Undo method (part of the TextBoxBase base class) that should provide what you need. WPF TextBox有一个Undo方法( TextBoxBase基类的一部分) ,它应该可以满足您的需求。

Undoes the most recent undo command.撤消最近的撤消命令。 In other words, undoes the most recent undo unit on the undo stack.换句话说,撤消撤消堆栈上最近的撤消单元。

Instead of attempting to send keystrokes to the control, just call the method on it:无需尝试将击键发送到控件,只需调用其上的方法:

        private void menu1_edit_undo_Click(
           object sender, RoutedEventArgs e)
        {
            textbox1.Undo();
        }

Ok... I found out you can do it my adding a Reference to System.Windows.Form to you WPF project, and then adding this to the Click handler:好的...我发现您可以通过向您的 WPF 项目添加对 System.Windows.Form 的引用,然后将其添加到 Click 处理程序中来做到这一点:

textbox1.Focus();
System.Windows.Form.SendKeys.SendWait("^z");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM