How to automatically generate a library of extension methods WPF Event & # 8594; IObservable

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.

+4
source share
1 answer

To get all types coming from FrameworkElement you can use

 var typesToDo = from t in Assembly.GetAssembly(typeof(FrameworkElement)).GetTypes() where t.IsSubclassOf(typeof(FrameworkElement)) && t.IsPublic && t.GetEvents().Any() select t; 

and then you can use type.GetEvents() to get events of each type. The returned EventInfo event allows you to view things like name, type, arguments, etc.

You need to do a little extra work to deal with generic events, but this is not a huge amount.

I put the sample program on GitHub along with the sample output .

There is a risk that some of the results do not work properly, I did not try all of them :) I did everything so that they built everything, and that at least some of them work correctly.

+6
source

All Articles