WPF——命令
阿新 • • 發佈:2021-01-15
命令同事件的區別
事件的作用是釋出、傳播一些訊息,訊息傳達到了接收者,事件的指令也就算完成了,至於接收者如何響應事件送來的訊息事件並不做任何限制(事件處理器是自己針對不同接收者自己編寫的),每個接收者可已用自己的行為來響應事件。
而命令如何處理是寫在命令裡面的(具體是命令關聯即偵察兵裡的),不由命令接收者的不同而不同。
舉個例子:
事件:在戰場上打仗的時候,將軍說前進,步兵向前跑,坦克發動引擎,炮兵揮揮手。以上行為均為不同接收者對將軍發出的前進事件的不同處理方式。
命令:將軍說前進,我不管你是什麼兵種,你的location屬性都得給我加1。
命令實現的流程圖
整個命令的實現流程非常像是炮彈轟炸對應目標的一個流程。
- 命令——炮彈
- 命令源——義大利炮
- 命令目標——轟炸目標(轟炸目標裡還有我們潛伏的同志,會給偵察兵傳送是否可以轟炸/是否轟炸完成等通知)
- 命令關聯——偵察兵
整個命令實現的流程分為兩個流程。
- 轟炸前確定目標,炮彈開啟保險;
- 轟炸後偵察兵傳回轟炸結果,並做後續行動。
轟炸前流程圖:
轟炸過程流程圖:
命令程式設計的流程
程式碼編寫的流程:
綠色為主要流程,藍色為要準備的材料
程式
XAML:
<Grid Name="grid">
<Grid.RowDefinitions>
<RowDefinition Height="24"/>
<RowDefinition Height="4"/>
<RowDefinition Height="24"/>
<RowDefinition Height="4"/>
<RowDefinition Height="24"/>
<RowDefinition Height="4"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="姓名:" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBox Grid.Row="0" Name="textbox" HorizontalAlignment="Right" Margin="0,2,2,2" Width="740"/>
<Button Grid.Row="2" Name="TeacherButton" Content="新建教師資訊" Margin="10 2" />
<Button Grid.Row="4" Name="StudentButton" Content="新建學生資訊" Margin="10 2" />
<ListBox Grid.Row="6" Name="ListBox" Margin="5"/>
</Grid>
CS:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitializeCommand();
}
private void InitializeCommand()
{
//將命令給命令源(將炮彈給發射炮,同一種炮彈裝的火藥不同,分別由兩門炮來打)
this.StudentButton.Command = ApplicationCommands.New;
this.StudentButton.CommandParameter = "Student";
this.TeacherButton.Command = ApplicationCommands.New;
this.TeacherButton.CommandParameter = "Teacher";
//設定命令目標(設定目標靶子)
this.TeacherButton.CommandTarget = this.textbox;
this.StudentButton.CommandTarget = this.textbox;
//建立並設定偵察兵屬性
//建立關聯命令(建立偵察兵)
CommandBinding commandBinding = new CommandBinding();
//給偵察兵指定的要關注以及通知的炮彈
commandBinding.Command = ApplicationCommands.New; //關注NEW這個炮彈 通知new這個炮彈戰場情況 NEW轟炸後傳出事件 例如刪除這種命令(炮彈)就不由這個偵察兵觀察情況傳遞命令了
//給偵察兵指定情況較好可以轟炸時的路由事件
commandBinding.CanExecute += new CanExecuteRoutedEventHandler(CommandBinding_CanExecute);
//給偵察兵指定轟炸完成後的路由事件
commandBinding.Executed += new ExecutedRoutedEventHandler(CommandBinding_Executed);
//把偵察兵放在高地上
this.window.CommandBindings.Add(commandBinding);
}
//指定 這種炮彈能發射事件
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (String.IsNullOrEmpty(this.textbox.Text))
{
e.CanExecute = false;
}
else
{
e.CanExecute = true;
}
}
//指定不同火藥型別炸彈炸完之後的後續行動
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
String name = this.textbox.Text;
if(e.Parameter.ToString() == "Student")
{
this.ListBox.Items.Add(String.Format("{0},好好學習天天向上", name));
}
if(e.Parameter.ToString() == "Teacher")
{
this.ListBox.Items.Add(String.Format("{0},好好學習天天向上", name));
}
}
}