3

How can I add a Xamarin.Forms XAML file to an FSharp project?

By default, XAML files have C# code-behind. I tried moving a XAML file with C# code-behind to an F# project. I then changed the file extension to ".fs". However, my attempt crashed VS2017.

Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • it works for me? you have examples in my repo https://github.com/knocte/gwallet/tree/frontend – knocte Mar 22 '18 at 16:29

2 Answers2

0

EDIT

C# Views & F# ViewModels

I'm guessing WPF and Xamarin.Forms will see this the same way. You can define all your views in your C# project and have your ViewModel logic in a Portable Class Library (PCL). You can refer your ViewModels directly in your C# project when the View needs its DataContext. This way, it'll behave the same way as it would with a C# ViewModel.

If you'd like a working example of this, I found this that shows exactly what you could do: MVVM with F#

F# MVVM

If you'd prefer to have an entire application that has F# business logic and XAML in the same project, you can download the following extension: Windows App in F#. By pointing to the FSharp.ViewModule in your directives, you'll be fine.

The view model which will handle all UI logic. Inherit view model from ViewModelBase

You'll also be able to find a working sample of this kind of thing right here

Kevin Avignon
  • 2,853
  • 3
  • 19
  • 40
0

"Code behind" files don't exist in F# (lack of partial classes), and even in C# many people recommend keeping those files empty.

You can load the Xaml file using .LoadFromXaml and access objects using .FindByName<'t>. See Wintellect sample. You need to specify the names as strings and the types so there isn't compile-time safety.

It is not as clean as on WPF, where there is a type provider (FsXaml) which gives typed access to the objects. A type provider for Xamarin Forms may appear in future.

I personally prefer to avoid Xaml and do everything in code, where everything is typed and there is no reliance on strings.

Charles Roddie
  • 952
  • 5
  • 16