F#没有WPF模板,实现.net7.0-windows需要手工实现,本文就是讲解如何新建一个F#WPF程序。

新建控制台应用程序。非(.net framework)

修改项目属性,项目文件(*.fsproj)代码如下:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net7.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
    <UseWindowsForms>False</UseWindowsForms>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MahApps.Metro" Version="2.4.9" />
    <PackageReference Include="System.Reactive" Version="5.0.0" />
  </ItemGroup>

</Project>

最简单的亮机启动代码,如下:

open System
open System.Windows
open System.Windows.Controls

let w = new Window()
let b = new Button(Content = "Hello from WPF!")
b.Click.Add(fun _ -> w.Close())
w.Content <- b

let a = new Application()

[<STAThread>]
do a.Run(w) |> ignore

略微复杂有用一些的代码。LOADING XAML INTO F# APPLICATIONS

let a = 
    let reader = XmlReader.Create(Path.Combine(__SOURCE_DIRECTORY__,"App.xaml"))
    XamlReader.Load(reader) :?> Application

let w = 
    let reader = XmlReader.Create(Path.Combine(__SOURCE_DIRECTORY__,"FirstMetroWindow.xaml"))
    let this = XamlReader.Load(reader) :?> Window
    let btn = this.FindName("btn") :?> Button
    btn.Click.Add(fun _ ->
        MessageBox.Show("click from code behind.") |> ignore
    )
    this

[<STAThread>]
do a.Run(w) |> ignore