当控件样式和控件应用不在同一个文件时,也就是说当样式写到一个独立的文件时;
如果需要在控件样式里触发某些事件,这事就需要绑定自定义的命令处理。
自定义命令代码如下:
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 }