I almost exclusively use Reactive Extensions in my WPF C # applications these days. Adding and removing event handlers is an anti-pattern, and I completely envy the fact that F # events implement IObservable.
To help C # developers, RX people provide the method below (and some others with different type security)
public static IObservable<EventPattern<TEventArgs>> FromEventPattern<TDelegate, TEventArgs> ( Action<TDelegate> addHandler , Action<TDelegate> removeHandler ) where TEventArgs : EventArgs
http://msdn.microsoft.com/en-us/library/hh211731(v=vs.103).aspx
I would use it like that
var movingEvents = Observable.FromEventPattern<MouseEventHandler, MouseEventArgs>(h => this.MouseMove += h, h => this.MouseMove -= h);
However, this is tiring. What I would like to do is
var movingEvents = h.MouseMoveObserver();
and get it over with. This extension method will look like
IObservable<MouseEventArgs> MouseMoveObserver(this Canvas This){ return Observable.FromEventPattern<MouseEventHandler, MouseEventArgs>(h => This.MouseMove += h, h => This.MouseMove -= h); }
This is not rocket science, and I was thinking of creating a library where I add these expansion methods one at a time when I need them. However, I am sure that some smart cookies can write a T4 template that processes all the controls in the WPF library through reflection and generates all the extension methods that I have ever needed. My question is ...
Has anyone written such a code generator to compare events with observables, as described above, and if someone had no suggestions on how to do this? I'm not that good at reflecting .Net, but some kind of seed code might make me start.