【WPF學習】第三十三章 高級命令


  前面兩章介紹了命令的基本內容,可考慮一些更復雜的實現了。接下來介紹如何使用自己的命令,根據目標以不同方式處理相同的命令以及使用命令參數,還將討論如何支持基本的撤銷特性。

一、自定義命令

  在5個命令類(ApplicationCommands、NavigationCommands、EditingCommands、ComponentCommands以及MediaCommands)中存儲的命令,顯然不會為應用程序提供所有可能需要的命令。幸運的是,可以很方便地自定義命令,需要做的全部工作就是實例化一個新的RoutedUiCommand對象。

  RoutedUICommand類提供了幾個構造函數。雖然可創建沒有任何附加信息的RoutedUICommand對象,但幾乎總是希望提供命令名、命令文本以及所屬類型。此外,可能希望為InputGestures集合提供快捷鍵。

  最佳設計方式是遵循WPF庫中的范例,並通過靜態屬性提供自定義命令。下面的示例定義了名為Requery的命令:

 public class DataCommands
    {
        private static RoutedUICommand requery;
        static DataCommands()
        {
            InputGestureCollection collection = new InputGestureCollection();
            collection.Add(new KeyGesture(Key.R, ModifierKeys.Control, "Ctrl+R"));
            requery = new RoutedUICommand("Requery", "Requery", typeof(DataCommands), collection);
        }

        public static RoutedUICommand Requery
        {
            get { return requery; }
            set { requery = value; }
        }
    }

  一旦定義了命令,就可以在命令綁定中使用它,就像使用WPF提供的所有預先構建好的命令那樣。但仍存在一個問題。如果希望在XAML中使用自定義的命令,那么首先需要將.NET名稱空間映射為XML名稱空間。例如,如果自定義的命令類位於Commands名稱空間中(對於名為Commands的項目,這是默認的名稱空間),那么應添加如下名稱空間映射:

xmlns:local="clr-namespace:Commands"

  這個示例使用local作為名稱空間的別名。也可使用任意希望使用的別名,只要在XAML文件中保持一致就可以了。

  現在,可通過local名稱空間訪問命令:

<CommandBinding Command="local:DataCommands.Requery" 
                Executed="CommandBinding_Executed">
</CommandBinding>

  下面是一個完整示例,在該例中有一個簡單的窗口,該窗口包含一個觸發Requery命令的按鈕:

<Window x:Class="Commands.CustomCommand"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Commands"
        Title="CustomCommand" Height="300" Width="300">
    <Window.CommandBindings>
        <CommandBinding Command="local:DataCommands.Requery" 
                        Executed="CommandBinding_Executed">
        </CommandBinding>
    </Window.CommandBindings>
    <Grid>
        <Button Margin="5" Command="local:DataCommands.Requery">Requery</Button>
    </Grid>
</Window>

  為完成該例,只需要在代碼中實現CommandBinding_Executed()事件處理程序即可。還可以使用CanExecute事件酌情啟用或禁用該命令。

二、在不同位置使用相同的命令

  在WPF命令模型中,一個重要概念是范圍(scope)。盡管每個命令僅有一份副本,但使用命令的效果卻會根據觸發命令的位置而異。例如,如果有兩個文本框,它們都支持Cut、Copy和Paste命令,操作只會在當前具有焦點的文本框中發生。

  至此,我們還沒有學習如何對自己關聯的命令實現這種效果。例如,設想創建了一個具有兩個文檔的控件的窗口,如下圖所示。

 

   如果使用Cut、Copy和Paste命令,就會發現他們能夠在正確的文本框中自動工作。然而,對於自己實現的命令——New、Open以及Save命令——情況就不同了。問題在於當為這些命令中的某個命令觸發Executed事件時,不知道該事件是屬於第一個文本框還是第二個文本框。盡管ExecuteRoutedEventArgs對象提供了Source屬性,但該屬性反映的是具有命令綁定的元素(像sender引用)。而到目前為止,所有命令都被綁定到了容器窗口。

  解決這個問題的方法是使用文本框的CommandBindings集合分別為每個文本框綁定命令。下面是一個示例:

<TextBox Margin="5" Grid.Row="3" TextWrapping="Wrap" AcceptsReturn="True"
             TextChanged="txt_TextChanged">
            <TextBox.CommandBindings>
                <CommandBinding Command="ApplicationCommands.Save"
          Executed="SaveCommand" />
            </TextBox.CommandBindings>
</TextBox>

  現在文本框處理Executed事件。在事件處理程序中,可使用這一信息確保保存正確的信息:

private void SaveCommand(object sender, ExecutedRoutedEventArgs e)
        {
            string text = ((TextBox)sender).Text;
            MessageBox.Show("About to save: " + text);
            isDirty= false;
        }

  上面的實現存在兩個小問題。首先,簡單的isDirty標記不在能滿足需要,因此現在需要跟蹤兩個文本框。有幾種解決這個問題的方法。可使用TextBox.Tag屬性存儲isDirty標志——使用該方法,無論何時調用CanExecuteSave()方法,都可以查看sender的Tag屬性。也可創建私有的字典集合來保存isDirty值,按照控件引用編寫索引。當觸發CanExecuteSave()方法時,查找屬於sender的isDirty值。下面是需要使用的完整代碼:

 private Dictionary<Object, bool> isDirty = new Dictionary<Object, bool>();
        private void txt_TextChanged(object sender, RoutedEventArgs e)
        {
            isDirty[sender] = true;
        }

        private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (isDirty.ContainsKey(sender) && isDirty[sender] == true)
            {
                e.CanExecute = true;
            }
            else
            {
                e.CanExecute = false;
            }
        }

  當前實現的另一個問題是創建了兩個命令綁定,而實際上只需要一個。這會是XAML文件更加混亂,維護起來更難。如果在這兩個文本框之間又大量的共享的命令,這個問題尤其明顯。

  解決方法是創建命令綁定,並向兩個文本框的CommandBindings集合中添加同一個綁定。使用代碼可很容易地完成該工作。如果希望使用XAML,需要使用WPF資源。在窗口的頂部添加一小部分標記,創建需要使用的Command Binding對象,並為之指定鍵名:

<Window.Resources>
        <CommandBinding  x:Key="binding" Command="ApplicationCommands.Save"
                         Executed="SaveCommand" CanExecute="SaveCommand_CanExecute">
        </CommandBinding>
    </Window.Resources>

  為在標記的另一個位置插入該對象,可使用StaticResource標記擴展並提供鍵名:

<TextBox.CommandBindings>
     <StaticResource ResourceKey="binding"></StaticResource>
</TextBox.CommandBindings>

  該示例的完整代碼如下所示:

<Window x:Class="Commands.TwoDocument"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TwoDocument" Height="300" Width="300">
    <Window.Resources>
        <CommandBinding  x:Key="binding" Command="ApplicationCommands.Save"
                         Executed="SaveCommand" CanExecute="SaveCommand_CanExecute">
        </CommandBinding>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition ></RowDefinition>
            <RowDefinition ></RowDefinition>
        </Grid.RowDefinitions>
        <Menu Grid.Row="0">
            <MenuItem Header="File">
                <MenuItem Command="New"></MenuItem>
                <MenuItem Command="Open"></MenuItem>
                <MenuItem Command="Save"></MenuItem>
                <MenuItem Command="SaveAs"></MenuItem>
                <Separator></Separator>
                <MenuItem Command="Close"></MenuItem>
            </MenuItem>
        </Menu>

        <ToolBarTray Grid.Row="1">
            <ToolBar>
                <Button Command="New">New</Button>
                <Button Command="Open">Open</Button>
                <Button Command="Save">Save</Button>
            </ToolBar>
            <ToolBar>
                <Button Command="Cut">Cut</Button>
                <Button Command="Copy">Copy</Button>
                <Button Command="Paste">Paste</Button>
            </ToolBar>
        </ToolBarTray>
        <TextBox Margin="5" Grid.Row="2" TextWrapping="Wrap" AcceptsReturn="True"
             TextChanged="txt_TextChanged">
            <TextBox.CommandBindings>
                <StaticResource ResourceKey="binding"></StaticResource>
            </TextBox.CommandBindings>
            <!--<TextBox.CommandBindings>
                <CommandBinding Command="ApplicationCommands.Save"
          Executed="SaveCommand" />
            </TextBox.CommandBindings>-->
        </TextBox>
        <TextBox Margin="5" Grid.Row="3" TextWrapping="Wrap" AcceptsReturn="True"
             TextChanged="txt_TextChanged">
            <TextBox.CommandBindings>
                <StaticResource ResourceKey="binding"/>
            </TextBox.CommandBindings>
            <!--<TextBox.CommandBindings>
                <CommandBinding Command="ApplicationCommands.Save"
          Executed="SaveCommand" />
            </TextBox.CommandBindings>-->
        </TextBox>
    </Grid>
</Window>
TwoDocument.xaml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Commands
{
    /// <summary>
    /// TwoDocument.xaml 的交互邏輯
    /// </summary>
    public partial class TwoDocument : Window
    {
        public TwoDocument()
        {
            InitializeComponent();
        }


        private void SaveCommand(object sender, ExecutedRoutedEventArgs e)
        {
            string text = ((TextBox)sender).Text;
            MessageBox.Show("About to save: " + text);
            isDirty[sender] = false;
        }

        private Dictionary<Object, bool> isDirty = new Dictionary<Object, bool>();
        private void txt_TextChanged(object sender, RoutedEventArgs e)
        {
            isDirty[sender] = true;
        }

        private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (isDirty.ContainsKey(sender) && isDirty[sender] == true)
            {
                e.CanExecute = true;
            }
            else
            {
                e.CanExecute = false;
            }
        }
    }
}
TwoDocument.xaml.cs

三、使用命令參數

  上面所有的示例都沒有使用命令參數來傳遞額外信息。然而,有些命令總需要一些額外信息。例如,NavigationCommands.Zoom命令需要用於縮放的百分數。類似地,可設想在特定情況下,前面使用過的一些命令可能也需要額外信息。例如,上節示例所示的兩個文本框編輯器使用Save命令,當保存文檔時需要知道使用哪個文件。

  解決方法是設置CommandParameter屬性。可直接為ICommandSource控件設置該屬性(甚至可使用綁定表達式從其他控件獲取值)。例如,下面的代碼演示了如何通過從另一個文本框中讀取數值,為鏈接到Zoom命令的按鈕設置縮放百分比:

<Button Command="NavigationCommands.Zoom"
    CommandParater="{Binding ElementName=txtZoom,Path=Text"}>
Zoom To Value
</Button>

  但該方法並不總是有效。例如,在具有兩個文件的文本編輯器中,每個文本框重用同一個Save按鈕,但每個文本框需要使用不同的文件名。對於此類情況,必須在其他地方存儲信息(例如,在TextBox.Tag屬性或在為區分文本框而索引文件名稱的單獨集合中存儲信息),或者需要通過代碼觸發命令,如下所示:

ApplicationCommands.New.Execute(theFileName,(Button)sender);

  無論使用哪種方法,都可以在Executed事件處理程序中通過ExecutedRoutedEventArgs.Parameter屬性獲取參數。

四、跟蹤和翻轉命令

  WPF命令模型缺少的一個特性是翻轉命令。盡管提供了ApplicationCommands.Undo命令,但該命令通常用於編輯控件(如TextBox控件)以維護它們自己的Undo歷史。如果希望支持應用程序范圍內的Undo特性,需要在內部跟蹤以前的狀態,並且觸發Undo命令時還原該狀態。

  遺憾的是,擴展WPF命令系統並不容易。相對來說沒幾個入口點用於連接自定義邏輯,並且對於可用的幾個入口點也沒有提供說明文檔。為創建通用的、可重用的Undo特性,需要創建一組全新的“能夠撤銷的”命令類,以及一個特定類型的命令綁定。本質上,必須使用自己創建的新命令系統替換WPF命令系統。

  更好的解決方案是設計自己的用於跟蹤和翻轉命令的系統,但使用CommandManager類保存命令歷史。下圖顯示了一個這方面的例子。在該例中,窗口包含兩個文本框和一個列表框,可以自由地再這兩個文本框中輸入內容,而列表框則一直跟蹤在這兩個文本框中發生的所有命令。可通過單擊Reverse Last Command按鈕翻轉最后一個命令。

 

   為構建這個解決方案,需要使用幾項新技術。第一細節是用於跟蹤命令歷史的類。為構建保存最近命令的撤銷系統,肯恩共需要用到這樣的類(甚至可能喜歡創建派生的ReversibleCommand類,提供諸如Unexecute()的方法來翻轉以前的任務)。但該系統不能工作,因為所有WPF命令都是唯一的。這意味着在應用程序中每個命令只有一個實例。

  為理解該問題,假設提供EditingCommands.Backspace命令,而且用戶在一行中回退了幾個空格。可通過向最近命令堆棧中添加Backspace命令來記錄這一操作,但實際上每次添加的是相同的命令對象。因此,沒有簡單的方法用於存儲命令的其他信息,例如剛剛刪除的字符。如果希望存儲該狀態,需要構建自己的數據結構。該例使用名為CommandHistoryItem的類。

  每個CommandHistoryItem對象跟蹤以下幾部分信息:

  •   命令名稱
  •   執行命令的元素。在該例中,有兩個文本框,所以可以是其中的任意一個。
  •   在目標元素中被改變的屬性。在該例中是TextBox類的Text屬性。
  •   可用於保存受影響元素以前狀態的對象(例如,執行命令之前文本框中的文本)。

  CommandHistoryItem類還提供了通用的Undo()方法。該方法使用反射為修改過的屬性應用以前的值,用於恢復TextBox控件中的文本。但對於更復雜的應用程序,需要使用CommandHistoryItem類的層次結構,每個類都可以使用不同方式翻轉不同類型的操作。

  下面是CommandHistoryItem類的完整代碼。

public class CommandHistoryItem
    {
        public string CommandName
        {
            get;
            set;
        }

        public UIElement ElementActedOn
        {
            get;
            set;
        }

        public string PropertyActedOn
        {
            get;
            set;
        }

        public object PreviousState
        {
            get;
            set;
        }

        public CommandHistoryItem(string commandName)
            : this(commandName, null, "", null)
        { }

        public CommandHistoryItem(string commandName, UIElement elementActedOn,
            string propertyActedOn, object previousState)
        {
            CommandName = commandName;
            ElementActedOn = elementActedOn;
            PropertyActedOn = propertyActedOn;
            PreviousState = previousState;
        }
        public bool CanUndo
        {
            get { return (ElementActedOn != null && PropertyActedOn != ""); }
        }

        public void Undo()
        {
            Type elementType = ElementActedOn.GetType();
            PropertyInfo property = elementType.GetProperty(PropertyActedOn);
            property.SetValue(ElementActedOn, PreviousState, null);
        }
    }

  需要的下一個要素是執行應用程序范圍內Undo操作的命令。ApplicationCommands.Undo命令時不適合的,原因是為了達到不同的目的,它已經被用於單獨的文本框控件(翻轉最后的編輯變化)。相反,需要創建一個新命令,如下所示:

private static RoutedUICommand applicationUndo;
        public static RoutedUICommand ApplicationUndo
        {
            get { return applicationUndo; }
        }

        static MonitorCommands()
        {
            applicationUndo = new RoutedUICommand("ApplicationUndo", "Application Undo", typeof(MonitorCommands));
            
        }

  在該例中,命令時在名為MonitorCommands的窗口類中定義的。

  到目前為止,出了執行Undo操作的反射代碼比較有意義外,其他代碼沒有什么值得注意的地方。更困難的部分是將該命令歷史集成進WPF命令模型中。理想的解決方案是使用能跟蹤任意命令的方式完成該任務,而不管命令是是被如何觸發和綁定的。相對不理想的解決方案是,強制依賴與一整套全新的自定義命令對象(這一邏輯功能內置到這些自定義命令對象中),或手動處理每個命令的Executed事件。

  響應特定的命令是非常簡單的,但當執行任何命令時如何進行響應呢?技巧是使用CommandManager類,該類提供了幾個靜態事件。這些事件包括CanExecute、PreviewCanExecute、Executed以及PreviewExecuted。在該例中,Executed和PreviewExecuted事件最有趣,因為每當執行任何一個命令時都會引發他們。

  盡管CommandManager類關起了Executed事件,但仍可使用UIElement.AddHandler()方法關聯事件處理程序,並為可選的第三個參數傳遞true值。這樣將允許接收事件,即使事件已經被處理過也同樣如此。然而,Executed事件是在命令執行完之后被觸發的,這時已經來不及在命令歷史中保存唄影響的控件的狀態了。相反,需要響應PreviewExecuted事件,該事件在命令執行前一刻被觸發。

  下面的代碼在窗口的構造函數中關聯PreviewExecuted事件處理程序,並當關閉窗口時解除關聯:

 public MonitorCommands()
        {
            InitializeComponent();
            this.AddHandler(CommandManager.PreviewExecutedEvent,
               new ExecutedRoutedEventHandler(CommandExecuted));
        }

        private void window_Unloaded(object sender, RoutedEventArgs e)
        {
            this.RemoveHandler(CommandManager.PreviewExecutedEvent,
               new ExecutedRoutedEventHandler(CommandExecuted));
        }

  當觸發PreviewExecuted事件時,需要確定准備執行的命令是否是我們所關心的。如果是,可創建CommandHistoryItem對象,並將其添加到Undo堆棧中。還需要注意兩個潛在的問題。第一個問題是,當單擊工具欄按鈕以在文本框上執行命令時,CommandExecuted事件被引發了兩次——一次是針對工具欄按鈕,另一次時針對文本框。下面的代碼通過忽略發送者是ICommandSource的命令,避免在Undo歷史中重復條目。第二個問題是,需要明確忽略不希望添加到Undo歷史中的命令。例如ApplicationUndo命令,通過該命令可翻轉上一步操作。

private void CommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            // 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);

                // CommandManager.InvalidateRequerySuggested();
            }
        }

  該例在ListBox控件中存儲所有CommandHistoryItem對象。ListBox控件的DisplayMember屬性被設置為true,因而會顯示每個條目的CommandHistoryItem.Name屬性。上面的代碼只為由文本框引發的命令提供Undo特性。然而,處理窗口中的任何文本框通常就足夠了。為了支持其他控件和屬性,需要對代碼進行擴展。

  最后一個細節是直線應用程序中范圍內Undo操作的代碼。使用CanExecute事件處理程序,可確保只有當在Undo歷史中至少有一項時,才能執行此代碼:

 private void ApplicationUndoCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (lstHistory == null || lstHistory.Items.Count == 0)
                e.CanExecute = false;
            else
                e.CanExecute = true;
        }

  為恢復最近的修改,只需要調用CommandHistoryItem對象的Undo方法。然后從列表中刪除該項即可:

private void ApplicationUndoCommand_Executed(object sender, RoutedEventArgs e)
        {
            CommandHistoryItem historyItem = (CommandHistoryItem)lstHistory.Items[lstHistory.Items.Count - 1];
            if (historyItem.CanUndo) historyItem.Undo();
            lstHistory.Items.Remove(historyItem);
        }

  到此,該示例的所有涉及細節都已經處理完成,該應用程序具有幾個完全支持Undo特性的控件,但要在實際應用程序中使用這一方法,還需要進行許多改進。例如,需要耗費大量時間改進CommandManager.PreviewExecuted事件的處理程序,以忽略那些明星不需要跟蹤的命令(當前,諸如使用鍵盤選擇文本的事件已經單擊空格鍵引發的命令等)。類似地,可能希望為那些不是由命令表示的但應當被翻轉的操作添加CommandHistoryItem對象。例如,輸入一些文本,然后導航到其他控件等。

  本實例完整代碼如下所示:

<Window x:Class="Commands.MonitorCommands"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Commands"
        Title="MonitorCommands" Height="300" Width="329.323" Unloaded="window_Unloaded">
    <Window.CommandBindings>

        <CommandBinding Command="local:MonitorCommands.ApplicationUndo"
                    Executed="ApplicationUndoCommand_Executed"
                    CanExecute="ApplicationUndoCommand_CanExecute"></CommandBinding>
    </Window.CommandBindings>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>


        <ToolBarTray  Grid.Row="0">
            <ToolBar>
                <Button Command="ApplicationCommands.Cut">Cut</Button>
                <Button Command="ApplicationCommands.Copy">Copy</Button>
                <Button Command="ApplicationCommands.Paste">Paste</Button>
                <Button Command="ApplicationCommands.Undo">Undo</Button>
            </ToolBar>
            <ToolBar Margin="0,0,-23,0">
                <Button Command="local:MonitorCommands.ApplicationUndo">Reverse Last Command</Button>
            </ToolBar>
        </ToolBarTray>
        <TextBox Margin="5" Grid.Row="1"
             TextWrapping="Wrap" AcceptsReturn="True">
        </TextBox>
        <TextBox Margin="5" Grid.Row="2"
             TextWrapping="Wrap" AcceptsReturn="True">
        </TextBox>
        <ListBox Grid.Row="3" Name="lstHistory" Margin="5" DisplayMemberPath="CommandName"></ListBox>
    </Grid>
</Window>
MonitorCommands.xaml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Commands
{
    /// <summary>
    /// MonitorCommands.xaml 的交互邏輯
    /// </summary>
    public partial class MonitorCommands : Window
    {
        private static RoutedUICommand applicationUndo;
        public static RoutedUICommand ApplicationUndo
        {
            get { return applicationUndo; }
        }

        static MonitorCommands()
        {
            applicationUndo = new RoutedUICommand("ApplicationUndo", "Application Undo", typeof(MonitorCommands));
            
        }
        public MonitorCommands()
        {
            InitializeComponent();
            this.AddHandler(CommandManager.PreviewExecutedEvent,
               new ExecutedRoutedEventHandler(CommandExecuted));
        }

        private void window_Unloaded(object sender, RoutedEventArgs e)
        {
            this.RemoveHandler(CommandManager.PreviewExecutedEvent,
               new ExecutedRoutedEventHandler(CommandExecuted));
        }

        private void CommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            // 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);

                // CommandManager.InvalidateRequerySuggested();
            }
        }

        private void ApplicationUndoCommand_Executed(object sender, RoutedEventArgs e)
        {
            CommandHistoryItem historyItem = (CommandHistoryItem)lstHistory.Items[lstHistory.Items.Count - 1];
            if (historyItem.CanUndo) historyItem.Undo();
            lstHistory.Items.Remove(historyItem);
        }

        private void ApplicationUndoCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (lstHistory == null || lstHistory.Items.Count == 0)
                e.CanExecute = false;
            else
                e.CanExecute = true;
        }
    }

    public class CommandHistoryItem
    {
        public string CommandName
        {
            get;
            set;
        }

        public UIElement ElementActedOn
        {
            get;
            set;
        }

        public string PropertyActedOn
        {
            get;
            set;
        }

        public object PreviousState
        {
            get;
            set;
        }

        public CommandHistoryItem(string commandName)
            : this(commandName, null, "", null)
        { }

        public CommandHistoryItem(string commandName, UIElement elementActedOn,
            string propertyActedOn, object previousState)
        {
            CommandName = commandName;
            ElementActedOn = elementActedOn;
            PropertyActedOn = propertyActedOn;
            PreviousState = previousState;
        }
        public bool CanUndo
        {
            get { return (ElementActedOn != null && PropertyActedOn != ""); }
        }

        public void Undo()
        {
            Type elementType = ElementActedOn.GetType();
            PropertyInfo property = elementType.GetProperty(PropertyActedOn);
            property.SetValue(ElementActedOn, PreviousState, null);
        }
    }
}
MonitorCommands.xaml.cs

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM