共用方式為


F# WPF Project Template

This template is for a basic F# Windows Presentation Foundation (WPF) project. This template can be found on the Visual Studio Gallery:

https://visualstudiogallery.msdn.microsoft.com/33dab4ce-62b8-419e-8072-92bc88556f78

When the template is installed you get the following template added to your F# folder when creating a new F# project:

image

This template that defines the following project elements:

  • MainWindow.fs: This is a module that has a single initControls() function that take in a Window element. The module provides a TODO tag showing the location for processing window elements and hooking up window events.
  • MainWindow.xaml: The XAML for the main window of the application.
  • App.xaml: XAML used for starting up the MainWindow window.
  • Program.fs: This controls the displaying of the window and ensures the STA Thread is used.

The MainWindow.fs file provides the structure for processing the window elements.

The MainWindow.fs code listing is:

module MainWindow =

    // Used to find elements
    let (?) (window : Window) name = window.FindName name |> unbox  

    // TODO initialize your controls
    let initControls (window:Window) =

        let mainButton : Button = window?MainButton
        let mainButtonText : TextBlock = window?MainButtonText

        mainButtonText.Text <- "Click here..."

        mainButton.Click
        |> Event.add (fun _ -> mainButtonText.Text <- "I've been clicked!")

        ()

It demonstrates processing of window elements and how to add events for these elements.

The Program.fs code is:

module Main =

    [<STAThread>]
    [<EntryPoint>]
    do
        let application = Application.LoadComponent(new Uri("App.xaml", UriKind.Relative)) :?> Application        

        // Ensure window can be processed
        application.Activated
        |> Event.add (fun _ -> MainWindow.initControls application.MainWindow)

        application.Run() |> ignore

The purpose of this code is rendering the main application window and calling the initControls() code.