Esempio n. 1
0
        public static IObservable <EventPattern <TEventArgs> > RoutedEventRaised <TDelegate, TEventArgs>(
            this UIElement element,
            RoutedEvent @event,
            bool handledEventsToo)
            where TEventArgs : RoutedEventArgs
        {
            Contract.Requires(element != null);
            Contract.Requires(@event != null);
            Contract.Ensures(Contract.Result <IObservable <EventPattern <TEventArgs> > >() != null);

            return(Observable.Create <EventPattern <TEventArgs> >(
                       observer =>
            {
                RoutedEventHandler handler = (sender, e) => observer.OnNext(new EventPattern <TEventArgs>(sender, (TEventArgs)e));

#if UNIVERSAL
                var d = handler.GetMethodInfo().CreateDelegate(typeof(TDelegate), handler.Target);
#else
                var d = Delegate.CreateDelegate(typeof(TDelegate), handler.Target, handler.Method);
#endif

                /* Silverlight throws an ArgumentException with the word "handler" as the message if the handler is
                 * not the exact type used by the specified routed event.  Therefore, it is necessary for this extension
                 * method to have a TDelegate type parameter so that it can create the proper handler type via reflection.
                 *
                 * TODO: Already tested for WP 7.1 but not tested yet for WP 8.0, so TDelegate might not be required anymore.
                 */
                element.AddHandler(@event, d, handledEventsToo);

                return Disposable.Create(() => element.RemoveHandler(@event, d));
            }));
        }