首页 > 解决方案 > 使用 WPF 中的按钮调用 F# 函数(FsXaml 方法)

问题描述

我正在尝试使用 F#、WPF 和 FsXaml 制作一个 Button Hello World 应用程序。我开始遵循本指南:

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

当我在 xaml 上加载内容并编译时,一切正常,但我没有设法通过按下按钮来调用函数,并且在他解释如何调用函数之前指南结束。

我已经看到了很多不同类型的方法,但还没有什么对我有用(而且许多指南已有多年历史,所以从那以后在框架内发生了很多事情)。一旦我理解了使用 FsXaml 时 x.xaml 和 x.xaml.fs 之间的逻辑,如果有一个工作(且简单)的起点,我就可以开始构建它会很棒。

我在 MainWindow.xaml 上的按钮:

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

我在 MainWindow.xaml 的 window 部分也有这个:

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

我的 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

我目前得到的错误:

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.

标签: wpff#fsxaml

解决方案


这就是我在 VS 2017 中进行的方式,对我来说它有效。我添加了UIAutomationTypes引用并安装了 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    

推荐阅读