天天看點

潛移默化學會WPF--Command(指令)學習(一) - AYUI架構 - 部落格園

潛移默化學會WPF--Command(指令)學習(一) - AYUI架構 - 部落格園 原文: 潛移默化學會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 好文要頂 關注我 收藏該文

潛移默化學會WPF--Command(指令)學習(一) - AYUI架構 - 部落格園
潛移默化學會WPF--Command(指令)學習(一) - AYUI架構 - 部落格園
潛移默化學會WPF--Command(指令)學習(一) - AYUI架構 - 部落格園

AYUI架構

關注 - 152

粉絲 - 841 +加關注 0 0 » 下一篇: 潛移默化學會WPF--Command(指令)學習(二)

posted on 2019-03-01 22:04 NET未來之路 閱讀( ...) 評論( ...) 編輯 收藏

轉載于:https://www.cnblogs.com/lonelyxmas/p/10459037.html