WPF Undo/Redo 按钮变灰

WPF Undo/Redo buttons turn grey

我正在使用 WPF 开发 UI,我想在应用程序操作中为 Undo/Redo 添加按钮。例如,如果我在 TextBox1 中输入一个值,而不是另一个值,通过按下撤消,它会返回到 textbox1 中的第一个值。

我尝试向按钮添加一个 Command="ApplicationCommands.Undo",但它变成灰色并且在 UI 上无法再点击:

<Button x:Name="undoBtn"
             BorderBrush="#FFABADB3"
             Background="{x:Null}"
             Padding="5,0,5,0"
             HorizontalAlignment="Left"
             Width="100"
             Height="25"
             VerticalAlignment="Top"
             Margin="15,130,0,0"
             Click='undoBtn_Click'
             Command="ApplicationCommands.Undo"
             >

我做错了什么? 非常感谢。

根据 ApplicationCommands class 的文档:

The commands in the ApplicationCommands class [...] only represent the instance of the RoutedCommand and not the implementation logic for the command. The implementation logic is bound to the command with a CommandBinding.

[... However, m]any controls do provide implementation logic for many of the commands in the command library. For example, the TextBox class provides logic for the Paste, Cut, Copy, Undo, and Redo commands.

要利用 TextBox class 提供的 Undo/Redo 命令的实现,请将命令的目标设置为 TextBox 元素。

<TextBox Name="TextBox1"/>
<Button Content="Undo" 
        Command="ApplicationCommands.Undo" 
        CommandTarget={Binding ElementName=TextBox1}"/>

为了回答您的问题,按钮未启用,因为 CanExecuteRoutedEventArgs for your CommandBinding's CanExecuteRoutedEventHandler 的 CanExecute 属性 未设置为 true,因为您的命令没有目标。