I wanted to create a bare bones WPF application using F#. There are several templates out there to create WPF apps in F# but they just added too much code from the outset for my liking.

So here are the steps to create a basic WPF F# application

  • Create a new project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add references to PresentationCore, PresentationFramework, System.Xaml and WindowsBase
  • Change the Program.fs to look like this
    open System
    open System.Windows
    open System.Windows.Controls
    open System.Windows.Markup
    
    [<STAThread>]
    [<EntryPoint>]
    let main argv = 
        let mainWindow = Application.LoadComponent(
                            new System.Uri("/<Your Assembly Name>;component/MainWindow.xaml", UriKind.Relative)) :?> Window
    
        let application = new Application()
        application.Run(mainWindow)
    

    Obviously change <Your Assembly Name> to the name of your compiled assembly name.

  • Add a new item to your project. Unfortunately there’s no XAML file (at least not in the version of Visual Studio I’m testing this on). So simply pick an XML File and give it the name MainWindow.xaml
  • In the MainWindow.xaml file replace the existing text with
    <Window 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
        </Grid>
    </Window>
    
  • Finally, select the MainWindow.xaml file in the solution explorer and change the file properties Build Action to Resource
  • And that’s all there is to getting a WPF F# application started.

    As F# doesn’t contain all the goodness of WPF templates and code behind etc. out of the box, it still might be better to create a C# WPF application then have all the view model’s etc. in a F# application if you want to, but this is a fairly good starting point if you prefer 100% F#.

    Addendum

    After working this stuff out and documenting it, I came across a post from MSDN Magazine titled Build MVVM Applications in F# which not only shows a more information on the approach I’ve outlined above, but also how to use F# to create view models etc.