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;
        }
    }

实现的效果是:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值