问题描述
如何从一个自定义路由事件中注销
How to DeRegister from one Custom Routed Event.
我有以下代码(自定义路由事件非常标准)
I have the following code (very standard for Custom Routed Events)
//Dispatch the Video Detection Movements
public delegate void MovementRoutedEventHandler( object sender
, MovementRoutedEventArgs e);
public class MovementRoutedEventArgs : RoutedEventArgs
{
private readonly DahuaDevice _device;
private readonly byte[] _canals;
private readonly DateTime _when;
public MovementRoutedEventArgs(DahuaDevice device, byte[] canals, DateTime when)
{
_device = device;
_canals = canals;
_when = when;
}
public DahuaDevice Device
{
get { return _device; }
}
public Byte[] Canals
{
get { return _canals; }
}
public DateTime When
{
get { return _when; }
}
}
public static RoutedEvent MovementEvent = EventManager.RegisterRoutedEvent(
"Movement"
, RoutingStrategy.Tunnel
, typeof(MovementRoutedEventHandler)
, typeof(Window)
);
public event RoutedEventHandler Movement
{
add { AddHandler(MovementEvent, value); }
remove { RemoveHandler(MovementEvent, value); }
}
public void RaiseMovementEvent(DahuaDevice device, byte[] canals, DateTime when)
{
RaiseEvent(new MovementRoutedEventArgs(device, canals, when)
{
RoutedEvent = MovementEvent
});
}
现在一个类将用这一行订阅这个事件:
Now a class will subscribe to this event with this line:
//Receive the Movement events
EventManager.RegisterClassHandler(
typeof(Window)
, Main.MovementEvent
, new Main.MovementRoutedEventHandler(MovementHandler));
当我关闭类实例时,我应该从事件中取消订阅(否则,实例不会垃圾收集)。
When I close the class instance, I should UnSubscribe from the event (otherwise, instance won't be garbage collected).
我应该叫什么?我试过 RegisterClassHandler(typeof(Window),Main.MovementEvent,** null **)
但是我收到一个例外...
What should I call? I tried RegisterClassHandler(typeof(Window), Main.MovementEvent, **null**)
but I get an exception...
任何帮助欢迎。感谢提前。
Any help welcome. Thanks in advance.
JM
推荐答案
您可以使用 RemoveHandler 方法来自UIElement类)
You can use RemoveHandler method from System.Windows.Window class (generally from UIElement class).
代码可能如下所示:
Main.RemoveHandler( Main.MovementEvent
, new Main.MovementRoutedEventHandler(MovementHandler));
这篇关于WPF定制路由事件 - 如何取消订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!