Home > database >  How to Convert RoutedEventHandler to EventHandler
How to Convert RoutedEventHandler to EventHandler

Time:08-31

I got this situation where I need to create a wrapper around a WPF window that exposes basic features, such as exposing Loaded and Closed events. (There are other wrapper implementations for other UI platforms)

// This works.
public event EventHandler? Closed
{
    add => Ref.Closed  = value;
    remove => Ref.Closed -= value;
}

// This doesn't work.
public event EventHandler? Loaded
{
    add => Ref.Loaded  = value;
    remove => Ref.Loaded -= value;
}

The problem here is that Loaded is a RoutedEventHandled (whereas Closing isn't). Settings an EventHandler doesn't work.

How can I solve this?

Edit: the only solution I can think of is to create a Dictionary of eventhandler wrappers when I add, so that I can get the same reference in remove. Any prettier solution?

CodePudding user response:

Subscribe to the Loaded event of Ref and raise your own custom event when it's raised:

public event EventHandler Loaded;
...
Ref.Loaded  = (ss, ee) => Loaded?.Invoke(this, EventArgs.Empty);

CodePudding user response:

I ended up doing this.

public event EventHandler? Loaded
{
    add
    {
        if (value != null)
        {
            var handler = new RoutedEventHandler((s, e) => value.Invoke(s, e));
            _loadedHandlers.Add(value, handler);
            Ref.Loaded  = handler;
        }
    }
    remove
    {
        if (value != null)
        {
            Ref.Loaded  = _loadedHandlers[value];
            _loadedHandlers.Remove(value);
        }
    }
}
private Dictionary<EventHandler, RoutedEventHandler> _loadedHandlers = new();
  • Related