private void CommandExecuted(object sender, ExecutedRoutedEventArgs e) { //当触发CommandManager.PreviewExecuted事件时,需要确定准备执行的命令是否是我们所关心的,如果是,可创建CommandHistoryItem对象,并将 //其添加到Undo堆栈中 //注意两个潜在问题: //1.当单击工具栏按钮以在文本框上执行命令时,CommandManager.PreviewExecuted事件被引发了两次——一次是针对工具栏按钮,另一次是针对文本框 //下面的代码通过忽略发送者是ICommandSource的命令,避免在Undo历史中重复条目 //2.需要明确忽略不希望添加到Undo历史中的命令 //例如ApplicationUndo命令,通过该命令可翻转上一步操作 // Ignore menu button source. if (e.Source is ICommandSource) { return; } // Ignore the ApplicationUndo command. if (e.Command == MonitorCommands.ApplicationUndo) { return; } // Could filter for commands you want to add to the stack (for example, not selection events) TextBox txt = e.Source as TextBox; if (txt != null) { RoutedCommand cmd = (RoutedCommand)e.Command; CommandHistoryItem historyItem = new CommandHistoryItem(cmd.Name, txt, "Text", txt.Text); ListBoxItem item = new ListBoxItem(); item.Content = historyItem; lstHistory.Items.Add(historyItem); //本例在ListBox控件中存储所有CommandHistoryItem对象。ListBox控件的DisplayMember属性被设置为Name,因而会显示每个条目的CommandHistoryItem.Name属性 //CommandManager.InvalidateRequerySuggested(); } }