-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventToCommandExtension
More file actions
88 lines (78 loc) · 3.27 KB
/
EventToCommandExtension
File metadata and controls
88 lines (78 loc) · 3.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/// <summary>
/// Расширение разметки для событий и команд
/// </summary>
[MarkupExtensionReturnType(typeof(RoutedEventHandler))]
public class EventHandlerExtension : MarkupExtension
{
Type _eventArgsType;
/// <summary>
/// Путь к команде
/// </summary>
public string BindingCommandPath { get; set; }
/// <summary>
/// Команда
/// </summary>
public ICommand Command { get; set; }
public EventHandlerExtension() { }
public EventHandlerExtension(string bindingCommandPath)
{
BindingCommandPath = bindingCommandPath;
}
public override object ProvideValue(IServiceProvider sp)
{
var pvt = sp.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
if (pvt != null)
{
var evt = pvt.TargetProperty as EventInfo;
var doAction = GetType().GetMethod("DoAction", BindingFlags.NonPublic | BindingFlags.Instance);
Type dlgType = null;
if (evt != null)
{
dlgType = evt.EventHandlerType;
}
var mi = pvt.TargetProperty as MethodInfo;
if (mi != null)
{
dlgType = mi.GetParameters()[1].ParameterType;
}
if (dlgType != null)
{
_eventArgsType = dlgType.GetMethod("Invoke").GetParameters()[1].ParameterType;
return Delegate.CreateDelegate(dlgType, this, doAction);
}
}
return null;
}
/// <summary>
/// Метод привязывающийся к событию
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DoAction(object sender, RoutedEventArgs e)
{
object obj = null;
var vm = (sender as FrameworkElement).DataContext;
if (BindingCommandPath != null)
{
var props = BindingCommandPath.Split('.');
foreach (var prop in props)
{
var property = vm.GetType().GetProperty(prop);
if (property != null)
vm = property.GetValue(vm, null);
else
{
MethodInfo method = vm.GetType().GetMethod(prop, BindingFlags.Public | BindingFlags.Instance);
if (method == null) throw new NotImplementedException("Класс расширения для событий может использоваться только с командами или методами");
method.Invoke(vm, new[] { sender, e });
return;
}
}
Command = vm as ICommand;
}
Type eventArgsType = typeof(EventCommandArgs<>).MakeGenericType(_eventArgsType);
var cmdParams = Activator.CreateInstance(eventArgsType, sender, e);
if (Command != null && Command.CanExecute(cmdParams))
Command.Execute(cmdParams);
}
}