潛移默化學會WPF--Command(命令)學習(一) - AYUI框架 - 博客園
1.Command心法
1.1 接觸
在窗體上可以定義<Window.CommandBindings>,這個跟 資源 類比,然後這樣定義
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.New"
Executed="NewCommand" />
</Window.CommandBindings>
這樣可以方便下面內容可以調用它,跟 資源 很像Command="ApplicationCommands.New" 表示新建,Command的值可以是其他的,例如復制(Copy),剪切(Cut)...至於其他的你可以自己試試,系統已經定義好的,當然你也可以自定義命令。 Executed 的值 是個事件名,也就是當你 按Ctrl+N 時,會執行後臺定義好的事件NewCommand裏面的方法。命令也可以這樣調用
1.2 潛移默化
<Menu>
<MenuItem Header="File">
<MenuItem Command="New"></MenuItem>
</MenuItem>
</Menu>
<Button Margin="5" Padding="5" Command="ApplicationCommands.New"
ToolTip="{x:Static ApplicationCommands.Copy}">New</Button>
1.3 具體代碼
<Window x:Class="Commands.TestNewCommand"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestNewCommand" Height="134" Width="281"
>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.New"
Executed="NewCommand" />
</Window.CommandBindings>
<StackPanel >
<Menu>
<MenuItem Header="File">
<MenuItem Command="New"></MenuItem>
</MenuItem>
</Menu>
<Button Margin="5" Padding="5" Command="ApplicationCommands.New"
ToolTip="{x:Static ApplicationCommands.Copy}">New</Button>
</StackPanel>
</Window>
後臺代碼
?using System; using System.Collections.Generic; 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 { public partial class TestNewCommand : System.Windows.Window { public TestNewCommand() { InitializeComponent(); } private void NewCommand( object sender, ExecutedRoutedEventArgs e) { MessageBox.Show( "New command triggered by " + e.Source.ToString()); } } } |
效果:
通過菜單單擊,或者按鈕單擊都會調用NewCommand這個方法,只不過事件源不一樣
補充:
默認 ApplicationCommands.New 會在菜單中顯示 新建 Ctrl+N 這種提示,你可以通過
ApplicationCommands.New.Text = "你想要的值";修改
你也可以後臺動態添加命令:
CommandBinding bindingNew = new CommandBinding(ApplicationCommands.New);
bindingNew.Executed += NewCommand;
this.CommandBindings.Add(bindingNew);
這個就不用我講解了吧,你懂的,呵呵。
下一章你將會掌握Command
潛移默化學會WPF--Command(命令)學習(一) - AYUI框架 - 博客園