Advantage of a FsXaml Provider over XamlReader

F # does not support partial classes or precompile XAML files. Workaround: instead of compiling time code, load the definitions of the graphic at runtime. There are various ways to provide XamlReader with the contents of a resource reference file.

open System.Windows // from Resource let uri = System.Uri "pack://application:,,,/AssemblyName;component/MainWindow.xaml" let info = Application.GetResourceStream uri let wnd = Markup.XamlReader.Load info.Stream :?> Window // from Embedded resource let assembly = System.Reflection.Assembly.GetExecutingAssembly() let stream = assembly.GetManifestResourceStream "MainWindow.xaml" let wnd = Markup.XamlReader.Load stream :?> Window 

Type providers should be able to defer at least some of this effort to compilation time.

 open FsXaml type MainWindow = XAML<"MainWindow.xaml"> let mainwnd = new MainWindow() let wnd = mainwnd.Root 

Enhancing security (and discovery) of the type seems marginal: one type of runtime that is less per resource. Are there any other benefits?

+5
source share
2 answers

Enhancing security (and discovery) of the type seems marginal: one type of runtime that is less per resource.

There are other advantages here, even in the code you displayed. Using FsXaml is much more concise in your example and completely safe. Also, compilation will fail if serious problems arise in your XAML files when using the XAML Loader cancels this at run time.

Are there any other benefits?

There are many benefits -

  • Shorter code
  • Security type
  • Named items displayed as properties in a safe type
  • (Most important) Creates actual types that match your XAML types

The last point is the really “killer” advantage of FsXaml vs XamlReader - without this, it's almost impossible to do anything other than “toy” projects in WPF. You need to have “real types” appropriate for your types if you want to implement XAML.

For example, if you want to use UserControls that you design as data templates, you need UserControl to be the actual type, and not just some XAML as a resource. Using XamlReader, there is no way to reference this from another XAML. You also cannot reuse resources, extract data into your application or many other things (without having to manually write a huge amount of plumbing to do this at runtime).

In addition, with FsXaml 2+, you can subclass types and provide complete logic inside the “code behind”, similarly (albeit differently) to how you work in C #.

This brings Xaml much closer to the C # experience. There is still no BAML compilation (one of the disadvantages), but otherwise you get experience that works well with C # when working with F # with WPF.

+7
source

The type provider checks everything at compile time, the Xaml reader works at runtime.
Thus, errors are either detected at compilation or at runtime. Obviously, finding bugs earlier in the development process is better.

+1
source

All Articles