WPF命令使用

来源:互联网 发布:知乎大学生推荐书单 编辑:程序博客网 时间:2024/05/16 06:31

What

命令包含以下部分:

命令:一个实现了ICommand接口的类,RoutedCommand是WPF里最常用的命令类,其它命令类大多派生自RoutedCommand

命令源:触发命令的对象,如button,menu等

命令目标:默认为命令源对象,显示指定CommandTarget=XXX之后,实际执行命令的对象为XXX,可通过执行函数的e.Source进行确认

命令关联:把命令源和命令以及命令的逻辑函数关联起来

 

why

命令可以实现一处定义,处处使用的好处。不同的命令源只要绑定同一个命令就会执行该命令绑定的执行函数。

解除前后端耦合,通过XAML绑定命令,后台代码类中可不再引用窗体控件

 

how

1、定义命令

?
1
public static ICommand AddCommand = newRoutedCommand();

  

2、定义命令执行函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void Add(objectsender, ExecutedRoutedEvente e)
{
    MessageBox.Show(e.Parameter.ToString());
 
    //标记为已处理,不再向上传递
    e.Handled =true;
}
public void CanAdd(objectsender, CanExecuteRoutedEvente e)
{
    if(string.IsNullOrEmpty(e.Parameter.ToString()))
        e.CanExecute =false;
    else
        e.CanExecute =true;
 
    e.Handled =true;
}

 

3、关联绑定命令和执行函数,并添加到控件的关联绑定集合

?
1
this.CommandBindings.Add(newCommandBinding(AddCommand, Add, CanAdd));

  

4、绑定命令源

?
1
2
3
<Button Content="clickme"
         Command="{x:Static local:TestWindow.AddCommand}"
         CommandParameter="{Binding Text ,ElementName=txtMsg}"/>

  

 

完整代码:

XAML

复制代码
<Window x:Class="WpfTest.TestWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        xmlns:local="clr-namespace:WpfTest"        mc:Ignorable="d"        Title="TestWindow" Height="300" Width="300">    <StackPanel>        <TextBox x:Name="txtMsg" Text="123" />        <!--第四步:把命令绑定到命令源-->            <Button Content="clickme"                 Command="{x:Static local:TestWindow.AddCommand}"                 CommandParameter="{Binding Text ,ElementName=txtMsg}" />    </StackPanel></Window>
复制代码

 

XAML.CS

复制代码
using System.Windows;using System.Windows.Input;namespace WpfTest{    /// <summary>    /// TestWindow.xaml 的交互逻辑    /// </summary>    public partial class TestWindow : Window    {        //第一步:定义命令        public static ICommand AddCommand = new RoutedCommand();        //第二步:定义执行函数        public void Add(object sender, ExecutedRoutedEvente e)        {            MessageBox.Show(e.Parameter.ToString());            //标记为已处理,不再向上传递            e.Handled = true;        }        public void CanAdd(object sender, CanExecuteRoutedEvente e)        {            if (string.IsNullOrEmpty(e.Parameter.ToString()))                e.CanExecute = false;            else                e.CanExecute = true;            e.Handled = true;        }        public TestWindow()        {            InitializeComponent();            //第三步:关联命令和执行函数,并添加到窗体的命令绑定集            this.CommandBindings.Add(new CommandBinding(AddCommand, Add, CanAdd));        }    }}
复制代码