Calling F# function with a button from WPF (FsXaml approach)

1

I'm trying to make a Button Hello World application with F#, WPF and FsXaml. I started following this guide:

https://www.c-sharpcorner.com/article/create-wpf-application-with-f-sharp-and-fsxaml/

Everything works fine when I just load things on xaml and compile, but I haven't managed to call a function by pressing a button and the guide ends before he explains how to call functions.

I've seen a lot of different kind of approaches around, but nothing has worked for me yet (and many of the guides are years old so a lot has happened inside frameworks since). It would be great to have a working (and simple) starting point on which I could start building once I understand the logic between x.xaml and x.xaml.fs when using FsXaml.

My button on MainWindow.xaml:

<Button x:Name="submitButton" Content="Send" Click="submitButton_Click"/>

Also I have this in window -section of MainWindow.xaml:

xmlns:local="clr-namespace:Views;assembly=GUItemplate"

My MainWindow.xaml.fs:

namespace GUItemplate

open FsXaml  
open System.Windows

type MainWindowBase = XAML<"MainWindow.xaml">

type MainWindow() =
    inherit MainWindowBase()

    override this.submitButton_Click (sender: obj, e: RoutedEventArgs) = 
        MessageBox.Show("Hello world!")
        |> ignore

The error I get currently:

System.Windows.Markup.XamlParseException
HResult=0x80131501
Message='Failed to create a 'Click' from the text 'submitButton_Click'.' Line number '29' and line position '101'.
Source=PresentationFramework

Inner Exception 1:
ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
wpf
f#
fsxaml
asked on Stack Overflow Jan 9, 2019 by A. Soikkeli • edited Jan 9, 2019 by A. Soikkeli

1 Answer

1

This is how I proceed in VS 2017 and for me it works. I add the UIAutomationTypes reference and I install the NuGet FsXaml.Wpf.

open System
open System.Windows
open FsXaml

type MainWindowBase = XAML<"MainWindow.xaml">

type MainWindow() =
    inherit MainWindowBase()

    override this.submitButton_Click (sender: obj, e: RoutedEventArgs) = 
        MessageBox.Show("Hello world!")
        |> ignore

[<EntryPoint;STAThread>]  
let application = new Application() in
    let mainWindow = new MainWindow() in
        application.Run(mainWindow) |> ignore    
answered on Stack Overflow Jan 10, 2019 by Jean-Claude Colette

User contributions licensed under CC BY-SA 3.0