WPF Custom Routed Events - How to Unsubscribe?

How to derive from a single 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 the class will subscribe to this event using this line:

 //Receive the Movement events EventManager.RegisterClassHandler( typeof(Window) , Main.MovementEvent , new Main.MovementRoutedEventHandler(MovementHandler)); 

When I close the class instance, I have to unsubscribe from the event (otherwise the instance will not be garbage collected).

What should I call? I tried RegisterClassHandler(typeof(Window), Main.MovementEvent, **null**) , but getting an exception ...

Any help is appreciated. Thanks in advance.

Jm

+6
source share
2 answers

You can use the RemoveHandler method from the System.Windows.Window class (usually from the UIElement class).

The code might look something like this:

 Main.RemoveHandler( Main.MovementEvent , new Main.MovementRoutedEventHandler(MovementHandler)); 
+9
source

I'm not sure if I fully understand what you are doing, but I will drop my two cents.

Your call to EventManager.RegisterClassHandler must be placed in the static constructor for your class that you want to register. This applies to all your class instances and should not affect garbage collection.

If you want to register / unregister an event at the level of each instance, use the traditional

 myEvent += myDelegate; myEvent -= myDelegate; 

Hope this helps.

+5
source

Source: https://habr.com/ru/post/899911/


All Articles