F# : WPF Hello World

 

Hope you guys had a look at my other F# posts

In this post i am going to talk about how we can create a Hello World program in WPF using F#.

We would need to manually create and include XAML files in WPF projects, they could also be loaded from code at runtime. We would also need to write the code to hook up event handlers. Let’s get started.

  • Create a new F# application named HelloWorldWPF

 

Create WPF F# Project

Create WPF F# Project

  • There is no way add a xaml file to a console application so either you would need to create an xml file and start editing it or use any other tool (Like Expression Blend) to create a xaml file and then include it in the project. i have used the 2nd option
F# Add XAML File

F# Add XAML File

  •  You can have a look at the xaml file below:
F# XAML File

F# XAML File

  • Lets add the references required by the WPF application. Add a reference to PresentationCore, PresentationFramework, System.Data, System.Deployment
  • Open namespace System, System.Windows and System.Windows.Controls. The let keyword is used for simple values.
  • Create a function that will load my main windows. So lets create a function named loadMyWindow().
  • Then define a new Uri for loading our MainWindow.xaml. This is the standard .Net specification. We don’t need any line terminatio as F# terminaties lines automatically.
  • Then we create a window using the resource loaded in the resourceLocator and then we need to cast this to Window using the F# cast operator.
  • The we find Element which is our clickButton and and we add a function to the Click Event of the Button. In F# we need to also handle all the return vales and hence we have used F# helper function ignore to ignore the values. In F# the last keyword in the function is the return type of the fuction which in our case is a window.
  • Now we would pass this window to the Application.Run and we ignore the retun value as well. We also then apply the STAThread attribute.
WPF HelloWorld

WPF HelloWorld

  •  Now we run the application and this is what we see.
WPF HelloWorld

WPF HelloWorld

 

Any Feedback, comments or questions were most welcome.