1: public static class EventCommand
2: {
3: public static readonly DependencyProperty CommandProperty =
4: DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(EventCommand), new PropertyMetadata(null));
5:
6: public static ICommand GetCommand(DependencyObject d)
7: {
8: return (ICommand)d.GetValue(CommandProperty);
9: }
10:
11: public static void SetCommand(DependencyObject d, ICommand value)
12: {
13: d.SetValue(CommandProperty, value);
14: }
15:
16: public static readonly DependencyProperty RoutedEventProperty =
17: DependencyProperty.RegisterAttached("RoutedEvent", typeof(String),
18: typeof(EventCommand), new PropertyMetadata((String)String.Empty, new PropertyChangedCallback(OnRoutedEventNameChanged)));
19:
20:
21: public static String GetRoutedEvent(DependencyObject d)
22: {
23: return (String)d.GetValue(RoutedEventProperty);
24: }
25:
26: public static void SetRoutedEvent(DependencyObject d, String value)
27: {
28: d.SetValue(RoutedEventProperty, value);
29: }
30:
31:
32: private static void OnRoutedEventNameChanged(DependencyObject d,
33: DependencyPropertyChangedEventArgs e)
34: {
35: String routedEvent = (String)e.NewValue;
36: if (d == null || String.IsNullOrEmpty(routedEvent)) return;
37:
38: EventHooker eventHooker = new EventHooker();
39: EventInfo eventInfo = d.GetType().GetEvent(routedEvent, BindingFlags.Public | BindingFlags.Instance);
40: if (eventInfo != null)
41: {
42: eventInfo.RemoveEventHandler(d,
43: eventHooker.GetNewEventHandlerToRunCommand(eventInfo));
44:
45: eventInfo.AddEventHandler(d,
46: eventHooker.GetNewEventHandlerToRunCommand(eventInfo));
47: }
48: }
49: }
50:
51: sealed class EventHooker
52: {
53: public Delegate GetNewEventHandlerToRunCommand(EventInfo eventInfo)
54: {
55: return Delegate.CreateDelegate(eventInfo.EventHandlerType, this,
56: GetType().GetMethod("OnEventRaised", BindingFlags.NonPublic | BindingFlags.Instance));
57: }
58:
59: private void OnEventRaised(object sender, EventArgs e)
60: {
61: ICommand command = (ICommand)(sender as DependencyObject). GetValue(EventCommand.CommandProperty);
62: if (command != null) command.Execute(null);
63: }
64: }