1. 程式人生 > >WPF中的命令(二)- 命令中傳遞引數

WPF中的命令(二)- 命令中傳遞引數

在上一節中,new一個名叫Clear的RoutedCommand進行了命令繫結步驟的演示,其實在WPF中已經準備了一些便捷的命令庫,他們都是靜態類,包括了很多New、Close此類全域性的靜態的RoutedCommand。而這些命令可以用任何一個控制元件元素作為命令源,以New命令為例,全域性範圍內只有一個New命令,介面上有兩個button,每個button都可以傳送該命令。這時,問題就來了,我們怎麼區分每個button傳送的命令而分別new不同的物件呢?這時就需要CommandParameter,比如分別new一個Student物件和Teacher物件,我們只要將CommandParameter賦值不同的字串就可以了,如下:

<Window x:Class="_9_3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="New"  Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute"/>
    </Window.CommandBindings>
    <Grid>
        <Button Content="New Teacher" Height="23" HorizontalAlignment="Left" Margin="158,42,0,0" Name="button1" VerticalAlignment="Top" Width="159" 
                Command="New" CommandParameter="Teacher"/>
        <Button Content="New Student" Height="23" HorizontalAlignment="Left" Margin="158,82,0,0" Name="button2" VerticalAlignment="Top" Width="159" 
                Command="New" CommandParameter="Student"/>
        <ListBox Height="170" HorizontalAlignment="Left" Margin="12,129,0,0" Name="listBox1" VerticalAlignment="Top" Width="479" />
    </Grid>
</Window>

後臺程式碼:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Parameter.ToString() == "Teacher")
            {
                listBox1.Items.Add("New a Teacher");
            }
            else if (e.Parameter.ToString() == "Student")
            {
                listBox1.Items.Add("New a Student");
            }
        }

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
    }

實現的效果是: