public class AwaitableRoutedEvent
{
private TaskCompletionSource<object> _tcs;
public async Task When<TypeOfControl>(TypeOfControl source, string nameOfEvent)
{
_tcs = new TaskCompletionSource<object>();
var targetEventInfo = source.GetType().GetEvent(nameOfEvent);
Delegate tempEventHandler =
Delegate.CreateDelegate(
targetEventInfo.EventHandlerType,
GetType().GetMethod(nameof(RoutedEventHandler), BindingFlags.Instance | BindingFlags.Public));
try
{
targetEventInfo.AddEventHandler(source, tempEventHandler);
await _tcs.Task;
}
finally
{
targetEventInfo.RemoveEventHandler(source, tempEventHandler);
_tcs = null;
}
}
public void RoutedEventHandler(object sender, RoutedEventArgs arguments)
{
_tcs.TrySetResult(null);
}
}
上面的calss表示'等待'RoutedEventHandler
事件。目标是像await new AwaitableRoutedEvent().When(button_object, "click");
一样使用它。
如果我制作public void RoutedEventHandler(object sender, RoutedEventArgs arguments)
静态 ...并更改BindingsFlags
......就可以了。但我不喜欢静电。非静态版本引发异常:Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type
。
我错过了什么吗?
答案 0 :(得分:0)
因为RoutedEventHandler是一个实例方法,所以在创建委托时,您应该提供调用该方法的对象的实例:
> /var/log/sshd.log format=raw
? [= Facility auth] file sshd.log
看起来你根本不需要它,因为你可能会写
Delegate tempEventHandler =
Delegate.CreateDelegate(
targetEventInfo.EventHandlerType,
this,
GetType().GetMethod(nameof(RoutedEventHandler), BindingFlags.Instance | BindingFlags.Public));