Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to convert a WPF Button.Click Event into Observable using Rx and F#
    primarykey
    data
    text
    <p>I am trying to replicate some C# code which creates an <code>IObservable</code> from a <code>Button.Click</code> event. I want to port this code to F#.</p> <p>Here is the original C# code which compiles without errors:</p> <pre><code>Observable.FromEvent&lt;RoutedEventHandler, RoutedEventArgs&gt;( h =&gt; new RoutedEventHandler(h), h =&gt; btn.Click += h, h =&gt; btn.Click -= h)) </code></pre> <p>Here is my failing attempt to do the same in F#:</p> <pre><code>Observable.FromEvent&lt;RoutedEventHandler, RoutedEventArgs&gt;( Func&lt;EventHandler&lt;RoutedEventArgs&gt;, RoutedEventHandler&gt;(fun h -&gt; RoutedEventHandler(h)), Action&lt;RoutedEventHandler&gt;(fun h -&gt; btn.Click.AddHandler h), Action&lt;RoutedEventHandler&gt;(fun h -&gt; btn.Click.RemoveHandler h)) </code></pre> <p>Everything is happy except for the second line of the statement. </p> <p>The F# compiler complains about <code>fun h -&gt; RoutedEventHandler(h)</code> because it doesn't want to except <code>h</code> as a parameter to the <code>RoutedEventHandler</code> constructor.</p> <p>On th other hand the C# compiler seems to have no problem accepting <code>h =&gt; new RoutedEventHandler(h)</code></p> <p>Interestingly enough, in both code samples (C# and F#) the type of <code>h</code> is <code>EventHandler&lt;RoutedEventArgs&gt;</code>.</p> <p>The error message I am getting from the F# compiler is: </p> <blockquote> <p>Error 2 This expression was expected to have type obj -> RoutedEventArgs -> unit but here has type EventHandler </p> </blockquote> <p>The signature for <code>RoutedEventHandler</code> that I found inside PresentationCore is:</p> <p><code>public delegate void RoutedEventHandler(object sender, RoutedEventArgs e);</code></p> <p>As you can see it does take an <code>object</code> and <code>RoutedEventArgs</code> as parameters, so the F# compiler is actually correct. </p> <p>Is there some magic that the C# compiler does behind the scenes to make this work that the F# compiler doesn't or am I just missing something here?</p> <p>Either way, how can I make this work in F#?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload