wpf-基础-命令-命令参数

参考的是书籍《深入浅出WPF》。运行环境:win10+vs2019。除某些截图中的代码外,其他均已本地测试通过。

如果界面上有两个按钮,都使用New命令,如何区分?

因为New是单例啊。区分方法是使用CommandParameter。命令源是实现了ICommandSource接口的对象,它会有一个叫CommandParameter的属性,它带的信息足以区分同一名称的命令。

实例:同一命令使用命令参数区分

Name框为空时,两个按钮都禁用。
在这里插入图片描述
Name后面的框不为空时,按不同的按钮打印不同字符串。
在这里插入图片描述
前台

    <Grid Margin="6">
        <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 Text="Name:" VerticalAlignment="Center" HorizontalAlignment="Left" Grid.Row="0"/>
        <TextBox x:Name="nameTextBox" Margin="60,0,0,0" Grid.Row="0"/>
        <Button Content="New Teacher" Command="New" CommandParameter="Teacher" Grid.Row="2"/>
        <Button Content="New Student" Command="New" CommandParameter="Student" Grid.Row="4"/>
        <ListBox x:Name="listBoxNewItems" Grid.Row="6"/>
    </Grid>
    <Window.CommandBindings>
        <CommandBinding Command="New" CanExecute="CommandBinding_CanExecute"
                        Executed="CommandBinding_Executed"/>
    </Window.CommandBindings>

后台

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();            
        }
     //下面这两个函数是前端new的时候vs生成的   
        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.nameTextBox.Text))
                e.CanExecute = false;
            else
                e.CanExecute = true;
        }
        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            string name = this.nameTextBox.Text;
            if (e.Parameter.ToString() == "Teacher")
                this.listBoxNewItems.Items.Add(string.Format("New Teacher:{0}, 老师", name));
            if (e.Parameter.ToString() == "Student")
                this.listBoxNewItems.Items.Add(string.Format("New Student:{0}, 学生", name));
        }
    }

如果一个UI所关联的命令有可能根据某些条件改变,则可以使用Binding:

<Button x:Name="dynamicCmdBtn" Command="{Binding Path=ppp, Source=sss}" Content="cmd" />

不过大多数命令按钮都有相对应的图标表示固定含义,所以很少需要这样改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值