Funk
Funk

Reputation: 11221

Referencing event from .xaml file in .fs file

I want to declare an event in a XAML file and then add a handler in a fs file.

The upper part of the XAML file would be something like (MouseRightButtonDown):

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AboutStack" MouseRightButtonDown="AboutStack_MouseRightButtonDown"
Title="About" SizeToContent="WidthAndHeight">
    <StackPanel>...

The F# file contains:

open FsXaml

type MainWindow = XAML<"MainWindow.xaml", true> 
let mainwnd = new MainWindow()
let wnd = mainwnd.Root

Is there an easy way to make the link?

Upvotes: 3

Views: 182

Answers (1)

CaringDev
CaringDev

Reputation: 8551

As there's no code-behind you can't call the method from XAML but need to attach it from the outside:

let AboutStack_MouseRightButtonDown args =
    // do whatever you want, return unit

wnd.MouseRightButtonDown.Add(AboutStack_MouseRightButtonDown)

or e.g.

wnd.MouseRightButtonDown.Add(fun _ -> MessageBox.Show("Click!") |> ignore)

Another approach would be to use a model (DataContext) and bindings for raising commands, see e.g Visual Studio Template for F# Windows App (WPF, MVVM)

Upvotes: 3

Related Questions