3

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?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Funk
  • 10,976
  • 1
  • 17
  • 33

1 Answers1

3

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)

CaringDev
  • 8,391
  • 1
  • 24
  • 43
  • I agree, a design pattern is the way to go. [Event driven MVVM](http://marisks.net/2015/05/11/f-sharp-xaml-event-driven-mvvm/) looks intresting. – Funk Jun 16 '15 at 09:51
  • 2
    Note that, with FsXaml 2+, you can actually do this within the type itself. However, you still need to wire it up yourself, as I'm not providing direct wiring of events. I've considered this, but it'd require a lot of odd work for something that's of little benefit given the ease of using commands. /cc @Funk – Reed Copsey Jun 14 '16 at 18:13
  • @ReedCopsey I agree, there's no need for direct wiring when we got commands and can still do it in 'code behind'. Thanks for the upgrade, it smoothens things out. – Funk Jun 16 '16 at 08:46