前面兩章介紹了命令的基本內容,可考慮一些更復雜的實現了。接下來介紹如何使用本身的命令,根據目標以不一樣方式處理相同的命令以及使用命令參數,還將討論如何支持基本的撤銷特性。數據結構
1、自定義命令app
在5個命令類(ApplicationCommands、NavigationCommands、EditingCommands、ComponentCommands以及MediaCommands)中存儲的命令,顯然不會爲應用程序提供全部可能須要的命令。幸運的是,能夠很方便地自定義命令,須要作的所有工做就是實例化一個新的RoutedUiCommand對象。編輯器
RoutedUICommand類提供了幾個構造函數。雖然可建立沒有任何附加信息的RoutedUICommand對象,但幾乎老是但願提供命令名、命令文本以及所屬類型。此外,可能但願爲InputGestures集合提供快捷鍵。ide
最佳設計方式是遵循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名稱空間訪問命令:this
<CommandBinding Command="local:DataCommands.Requery" Executed="CommandBinding_Executed"> </CommandBinding>
下面是一個完整示例,在該例中有一個簡單的窗口,該窗口包含一個觸發Requery命令的按鈕:spa
<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事件酌情啓用或禁用該命令。設計
2、在不一樣位置使用相同的命令
在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>
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; } } } }
3、使用命令參數
上面全部的示例都沒有使用命令參數來傳遞額外信息。然而,有些命令總須要一些額外信息。例如,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屬性獲取參數。
4、跟蹤和翻轉命令
WPF命令模型缺乏的一個特性是翻轉命令。儘管提供了ApplicationCommands.Undo命令,但該命令一般用於編輯控件(如TextBox控件)以維護它們本身的Undo歷史。若是但願支持應用程序範圍內的Undo特性,須要在內部跟蹤之前的狀態,而且觸發Undo命令時還原該狀態。
遺憾的是,擴展WPF命令系統並不容易。相對來講沒幾個入口點用於鏈接自定義邏輯,而且對於可用的幾個入口點也沒有提供說明文檔。爲建立通用的、可重用的Undo特性,須要建立一組全新的「可以撤銷的」命令類,以及一個特定類型的命令綁定。本質上,必須使用本身建立的新命令系統替換WPF命令系統。
更好的解決方案是設計本身的用於跟蹤和翻轉命令的系統,但使用CommandManager類保存命令歷史。下圖顯示了一個這方面的例子。在該例中,窗口包含兩個文本框和一個列表框,能夠自由地再這兩個文本框中輸入內容,而列表框則一直跟蹤在這兩個文本框中發生的全部命令。可經過單擊Reverse Last Command按鈕翻轉最後一個命令。
爲構建這個解決方案,須要使用幾項新技術。第一細節是用於跟蹤命令歷史的類。爲構建保存最近命令的撤銷系統,肯恩共須要用到這樣的類(甚至可能喜歡建立派生的ReversibleCommand類,提供諸如Unexecute()的方法來翻轉之前的任務)。但該系統不能工做,由於全部WPF命令都是惟一的。這意味着在應用程序中每一個命令只有一個實例。
爲理解該問題,假設提供EditingCommands.Backspace命令,並且用戶在一行中回退了幾個空格。可經過向最近命令堆棧中添加Backspace命令來記錄這一操做,但實際上每次添加的是相同的命令對象。所以,沒有簡單的方法用於存儲命令的其餘信息,例如剛剛刪除的字符。若是但願存儲該狀態,須要構建本身的數據結構。該例使用名爲CommandHistoryItem的類。
每一個CommandHistoryItem對象跟蹤如下幾部分信息:
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>
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); } } }