首页 > 其他 > 详细

自定义命令(Command)

时间:2014-01-15 08:41:22      阅读:523      评论:0      收藏:0      [点我收藏+]

当控件样式和控件应用不在同一个文件时,也就是说当样式写到一个独立的文件时;

如果需要在控件样式里触发某些事件,这事就需要绑定自定义的命令处理。

自定义命令代码如下:

bubuko.com,布布扣
 1  
 2 
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Windows.Input;
 8 using System.Diagnostics.CodeAnalysis;
 9 
10 namespace Medcare_V5.Teaching.Common.BaseTypes
11 {
12     public class MyCommad<T1, T2> : ICommand
13     {
14         private Func<T1, bool> canExecuteMethod;
15         private Action<T2> executeMethod;
16 
17         public MyCommad(Func<T1, bool> canExecuteMethod, Action<T2> executeMethod)
18         {
19             this.executeMethod = executeMethod;
20             this.canExecuteMethod = canExecuteMethod;
21         }
22 
23         public MyCommad(Action<T2> executeMethod)
24         {
25             this.executeMethod = executeMethod;
26             this.canExecuteMethod = (x) => { return true; };
27         }
28 
29         public bool CanExecute(T1 parameter)
30         {
31             if (canExecuteMethod == null) return true;
32             return canExecuteMethod(parameter);
33         }
34 
35         public void Execute(T2 parameter)
36         {
37             if (executeMethod != null)
38             {
39                 executeMethod(parameter);
40             }
41         }
42 
43         public bool CanExecute(object parameter)
44         {
45             return CanExecute((T1)parameter);
46         }
47 
48         public void Execute(object parameter)
49         {
50             Execute((T2)parameter);
51         }
52         /// <summary>
53         /// Occurs when changes occur that affect whether the command should execute.
54         /// </summary>
55         public event EventHandler CanExecuteChanged
56         {
57             add
58             {
59                 if (canExecuteMethod != null)
60                 {
61                     CommandManager.RequerySuggested += value;
62                 }
63             }
64 
65             remove
66             {
67                 if (canExecuteMethod != null)
68                 {
69                     CommandManager.RequerySuggested -= value;
70                 }
71             }
72         }
73     }
74 }
View Code

自定义命令(Command)

原文:http://www.cnblogs.com/fengxingblog/p/fengxing2014110160331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!