Of course! This is an excellent question that gets to the heart of integrating the "side-effectful" world of UI events with the pure, declarative world of an Elmish program in FuncUI.
Yes, there is a very similar and powerful way to achieve this. While FuncUI doesn't have a built-in .Events().MouseMove attribute like ReactiveUI, you can easily create the same observable stream by combining FuncUI's lifecycle hooks with the standard F# reactive library, FSharp.Control.Reactive.
The key is to use Attr.onLoaded to get a reference to the underlying Avalonia control once it's created and then use Observable.fromEvent to convert its standard .NET event into an IObservable.
Here is a complete, step-by-step example of an Elmish program that tracks the mouse position over a Canvas.
Core Concepts
FSharp.Control.Reactive: This is the F# wrapper for .NET's Reactive Extensions (Rx.NET). It provides the Observable module, which is essential.
Observable.fromEvent: This is the magic function that takes a standard .NET event (like canvas.PointerMoved) and turns it into an IObservable<'T> that you can map, filter, and subscribe to.
Attr.onLoaded: A FuncUI attribute that lets you run a function when the underlying Avalonia control has been created and loaded into the visual tree. This is where you get access to the actual control instance to attach the event.
Attr.onUnloaded: The counterpart to onLoaded. It's crucial for cleaning up. When you subscribe to an observable, you get back an IDisposable. You must call .Dispose() on it when the component is destroyed to prevent memory leaks. onUnloaded is the perfect place for this.
Step-by-Step Example
1. Project Setup
Make sure you have the following NuGet packages installed in your F# project:
Avalonia.FuncUI
Avalonia.Desktop (or your target platform)
FSharp.Control.Reactive
2. The Elmish Code
Here is the complete code for a simple application.
module MouseTrackerApp
open System
open Avalonia
open Avalonia.Controls
open Avalonia.Input
open Avalonia.Layout
open Avalonia.FuncUI
open Avalonia.FuncUI.Elmish
open FSharp.Control.Reactive
// 1. MODEL: Define the state of your application
type Model =
{ mousePosition: Point option }
// 2. MSG: Define the messages that can update your state
type Msg =
| UpdateMousePosition of Point
| NoOp // A message to do nothing, useful for initialization
// 3. INIT: Define the initial state of your application
let init () : Model * Cmd<Msg> =
{ mousePosition = None }, Cmd.none
// 4. UPDATE: Define how messages update the model
let update (msg: Msg) (model: Model) : Model * Cmd<Msg> =
match msg with
| UpdateMousePosition pos ->
// Return the new model and no further commands
{ model with mousePosition = Some pos }, Cmd.none
| NoOp ->
model, Cmd.none
// 5. VIEW: Define the UI based on the model
let view (model: Model) (dispatch: Msg -> unit) : IView =
// This mutable cell will hold our subscription so we can dispose of it later.
// This is a common pattern for managing disposable resources in a declarative UI.
let subscription = ref None
DockPanel.create [
DockPanel.children [
// A label to display the current mouse position
Label.create [
Label.dock Dock.Top
Label.horizontalAlignment HorizontalAlignment.Center
Label.content (
match model.mousePosition with
| Some pos -> $"Mouse Position: {pos.X:F0}, {pos.Y:F0}"
| None -> "Move mouse over the canvas below"
)
]
// The Canvas that we will track mouse moves on
Canvas.create [
Canvas.background "LightBlue"
Canvas.minHeight 200.0
// *** THIS IS THE KEY PART ***
// Use onLoaded to get the control instance and set up the observable
Attr.onLoaded (fun (canvas: Canvas) ->
let mouseMoveObservable =
// Convert the PointerMoved event into an IObservable
Observable.fromEvent canvas.PointerMoved
let sub =
mouseMoveObservable
// Extract the position relative to the canvas
|> Observable.map (fun args -> args.GetPosition(canvas))
// Convert the Point into our Elmish Msg
|> Observable.map UpdateMousePosition
// Subscribe to the observable stream and dispatch messages
|> Observable.subscribe dispatch
// Store the subscription so we can dispose of it
subscription := Some sub
)
// *** AND THIS IS THE CRUCIAL CLEANUP PART ***
// Use onUnloaded to dispose of the subscription and prevent memory leaks
Attr.onUnloaded (fun _ ->
match !subscription with
| Some sub ->
printfn "Disposing mouse move subscription."
sub.Dispose()
subscription := None
| None -> ()
)
]
]
]
// 6. PROGRAM: Wire everything together
type Host() as this =
inherit HostWindow()
do
Program.mkSimple init update view
|> Program.withHost this
// Optional: for hot-reloading
// |> Program.withHotReload
|> Program.run
Explanation of the Key Section
Let's break down the attributes on the Canvas:
// ... inside Canvas.create [...]
Attr.onLoaded (fun (canvas: Canvas) ->
// 1. Get an IObservable from the standard .NET event
let mouseMoveObservable = Observable.fromEvent canvas.PointerMoved
// 2. Transform and subscribe
let sub =
mouseMoveObservable
|> Observable.map (fun args -> args.GetPosition(canvas)) // IObservable<PointerEventArgs> -> IObservable<Point>
|> Observable.map UpdateMousePosition // IObservable<Point> -> IObservable<Msg>
|> Observable.subscribe dispatch // Start listening and send Msgs
// 3. Store the IDisposable subscription for cleanup
subscription := Some sub
)
Attr.onUnloaded (fun _ ->
// 4. When the control is removed, dispose of the subscription
!subscription |> Option.iter (fun sub -> sub.Dispose())
)
Observable.fromEvent: This is the bridge. It listens to the canvas.PointerMoved event and pushes the PointerEventArgs into an observable stream. Note that in Avalonia, the generic mouse move event is PointerMoved, not MouseMove.
Observable.map: We use map twice. First, to transform the raw PointerEventArgs into a simple Point by getting its position relative to our canvas. Second, to wrap that Point in our UpdateMousePosition message constructor. This creates an IObservable<Msg>.
Observable.subscribe dispatch: This is the final step. We subscribe to the IObservable<Msg>. The dispatch function from our Elmish program is the perfect subscriber. Every time the observable produces a new Msg, it will be sent directly to our update function, triggering a state change and a UI re-render.
subscription and onUnloaded: This resource management is vital. The onLoaded/onUnloaded lifecycle hooks give you the imperative control needed to correctly manage the subscription's lifetime within the otherwise declarative FuncUI model.
This pattern is extremely powerful and can be used for any UI event, not just mouse moves. It's the standard F# way to integrate Rx.NET with UI frameworks that provide lifecycle hooks.