【问题标题】:Using ctrl+z keys to implement our own Undo method/function in WPF and disabling the default undo command使用 ctrl+z 键在 WPF 中实现我们自己的 Undo 方法/功能并禁用默认的 undo 命令
【发布时间】:2018-05-14 22:44:47
【问题描述】:

如何使用 ctrl+z (ApplicationCommand.Undo) 键来实现我们自己的撤消方法,而不是使用 WPF 中的默认命令。基本上用我们自己的 undo 方法替换默认命令。

例如:我想将 ctrl+z 命令绑定到我的方法: private void OnMenuItemUndo(object sender, RoutedEventArgs e) in xaml.cs 文件。

【问题讨论】:

标签: c# wpf mvvm


【解决方案1】:

下面是一个简单的方法。它假定公开了名为YourUndoCmd 的ICommand 类型属性的数据源对象已经绑定到TextBox 的祖先DataContext 属性之一。

<TextBox IsUndoEnabled="false">
    <TextBox.InputBindings>
        <KeyBinding Modifiers="Ctrl" Key="Z" Command="{Binding YourUndoCmd}"/>
    </TextBox.InputBindings>  
</TextBox>

更新

CommandBinding 方式。

<Grid>
    <Grid.CommandBindings>
        <CommandBinding Executed="Undo_ExeCuted" Command="ApplicationCommands.Undo"/>
    </Grid.CommandBindings>

    <!--TextBox that will use your undo logic.-->
    <TextBox IsUndoEnabled="False"/>

    <!--TextBox that will use build-in undo logic.-->
    <TextBox />
</Grid>

在您的代码隐藏中,应该有一个类似下面的方法来处理撤消命令。

private void Undo_Executed(object sender, ExecutedRoutedEventArgs e)

【讨论】:

  • 所以我的方法:private void OnMenuItemUndo(object sender, RoutedEventArgs e) 应该在继承ICommand 的MyUndoCmd 类中?
  • 如果您坚持在代码隐藏中处理“撤消”,您也可以使用CommandBinding 将“撤消”RoutedUICommand 重定向到您指定的ExecutedRoutedEventHandler。我会更新我的答案。
  • 您更新的解决方案完美运行!非常感谢你。 :)
猜你喜欢
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 2019-07-18
  • 2021-11-26
  • 2021-09-15
相关资源
最近更新 更多