接实现ICommand接口的命令。在介绍之前,先看一下ICommand接口的原型:

  • event EventHandler CanExecuteChanged;
  • bool CanExecute(object parameter);
  • void Execute(object parameter);

  其中第一个事件为,当命令可执行状态发生改变时,可以激化此事件来通知其他对象。另外两个方法在上面已经用过同名的,在此不做重复说明。下面开始实现一个自定义直接实现ICommand接口的命令,同样实现点击源控件,清除目标控件的内容:

 1  //为了使目标控件,含有Clear()方法,所以在此一个定义接口
 2     public interface IView
 3     {
 4         void Clear();
 5     }
 6     
 7     //定义命令
 8     public class ClearCommand : ICommand
 9     {
10         public event EventHandler CanExecuteChanged;
11 
12         public bool CanExecute(object parameter)
13         {
14             throw new System.NotImplementedException();
15         }
16 
17         public void Execute(object parameter)
18         {
19             IView view = parameter as IView;
20             if (view != null)
21             {
22                 view.Clear();
23             }
24         }
25     }
26 
27     //自定义命令源
28     public class MyCommandSource : System.Windows.Controls.UserControl, ICommandSource
29     {
30         public ICommand Command { get; set; }
31 
32         public object CommandParameter { get; set; }
33 
34         public IInputElement CommandTarget { get; set; }
35 
36         //重写点击处理函数,注意由于事件的优先级不同,如果命令源是button的话,下面的函数不起作用
37         protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
38         {
39             base.OnMouseLeftButtonDown(e);
40 
41             if (this.CommandTarget != null)
42             {
43                 this.Command.Execute(this.CommandTarget);
44             }
45         }
46     }

 

相关文章:

  • 2022-02-07
  • 2021-06-21
  • 2022-12-23
  • 2021-11-17
  • 2021-08-28
  • 2021-07-18
猜你喜欢
  • 2022-12-23
  • 2021-07-17
  • 2022-12-23
  • 2022-01-18
  • 2021-11-10
相关资源
相似解决方案