Elmish.WPF
4.0.0-beta-54
See the version list below for details.
dotnet add package Elmish.WPF --version 4.0.0-beta-54
NuGet\Install-Package Elmish.WPF -Version 4.0.0-beta-54
<PackageReference Include="Elmish.WPF" Version="4.0.0-beta-54" />
paket add Elmish.WPF --version 4.0.0-beta-54
#r "nuget: Elmish.WPF, 4.0.0-beta-54"
// Install Elmish.WPF as a Cake Addin #addin nuget:?package=Elmish.WPF&version=4.0.0-beta-54&prerelease // Install Elmish.WPF as a Cake Tool #tool nuget:?package=Elmish.WPF&version=4.0.0-beta-54&prerelease
WPF done the Elmish Way
<img src="https://raw.githubusercontent.com/elmish/Elmish.WPF/master/logo/elmish-wpf-logo-ghreadme.png" width="300" align="right" />
The good parts of MVVM (the data bindings) with the simplicity and robustness of an MVU architecture for the rest of your app. Never write an overly-complex ViewModel class again!
Elevator pitch
Elmish.WPF is a production-ready library that allows you to write WPF apps with the robust, simple, well-known, and battle-tested MVU architecture, while still allowing you to use all your XAML knowledge and tooling to create UIs.
Some benefits of MVU you’ll get with Elmish.WPF include:
- Simple-to-understand, unidirectional data flow
- Single source of truth for all the state in your app
- Simple async/IO
- Immutable data
- Pure functions
- Great testability
- Simple optimization
- 78% more rockets 🚀
Even with static views, your central model/update code can follow an idiomatic Elmish/MVU architecture. You could, if you wanted, use the same model/update code to implement an app using a dynamic UI library such as Fabulous or Fable.React, by just rewriting the “U” part of MVU.
Static XAML views is a feature, not a limitation. See the FAQ for several unique benefits to this approach!
Elmish.WPF uses Elmish, an F# implementation of the MVU message loop.
Big thanks to @MrMattSim for the wonderful logo!
Sponsor
Thanks to JetBrains for sponsoring Elmish.WPF with OSS licenses!
Recommended resources
- The Elmish.WPF tutorial explains how to use Elmish.WPF, starting with general Elmish/MVU concepts and ending with complex optimizations.
- The Elmish.WPF binding reference explains Elmish.WPF's bindings and library functions for modifying bindings.
- The Elmish docs site also explains the general MVU architecture and principles.
- The Elmish.WPF samples provide many concrete usage examples.
- Blog posts:
- Getting Elmish in .NET with Elmish.WPF ("getting started" guide by Matt Eland)
- Elm resources may also provide some guidance, but note that not everything is relevant. A significant difference between “normal” Elm architecture and Elmish.WPF is that in Elmish.WPF, the views are statically defined using XAML, and the “view” function does not render views, but set up bindings. See the tutorial for details.
Getting started with Elmish.WPF
See the SingleCounter sample for a very simple app. The central points are (assuming up-to-date VS2019):
Create an F# Class Library. If targeting .NET 5 or .NET Core, the project file should look like this:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net5.0-windows</TargetFramework> <UseWpf>true</UseWpf> </PropertyGroup>
If targeting .NET Framework (4.6.1 or later), replace the first line with
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
Add NuGet reference to package
Elmish.WPF
.Define the model that describes your app’s state and a function that initializes it:
type Model = { Count: int StepSize: int } let init () = { Count = 0 StepSize = 1 }
Define the various messages that can change your model:
type Msg = | Increment | Decrement | SetStepSize of int
Define an
update
function that takes a message and a model and returns an updated model:let update msg m = match msg with | Increment -> { m with Count = m.Count + m.StepSize } | Decrement -> { m with Count = m.Count - m.StepSize } | SetStepSize x -> { m with StepSize = x }
Define the “view” function using the
Bindings
module. This is the central public API of Elmish.WPF.Normally in Elm/Elmish this function is called
view
and would take a model and a dispatch function (to dispatch new messages to the update loop) and return the UI (e.g. a HTML DOM to be rendered), but in Elmish.WPF this function is in general only run once and simply sets up bindings that XAML-defined views can use. Therefore, let’s call itbindings
instead ofview
.open Elmish.WPF let bindings () = [ "CounterValue" |> Binding.oneWay (fun m -> m.Count) "Increment" |> Binding.cmd (fun m -> Increment) "Decrement" |> Binding.cmd (fun m -> Decrement) "StepSize" |> Binding.twoWay( (fun m -> float m.StepSize), (fun newVal m -> int newVal |> SetStepSize)) ]
The strings identify the binding names to be used in the XAML views. The Binding module has many functions to create various types of bindings.
Alternatively, use statically-typed view models in order to get better IDE support in the XAML.
open Elmish.WPF type CounterViewModel(args) = inherit ViewModelBase<Model, Msg>(args) member _.CounterValue = base.Get() (Binding.OneWayT.id >> Binding.mapModel (fun m -> m.Count)) member _.Increment = base.Get() (Binding.CmdT.setAlways Counter.Increment) member _.Decrement = base.Get() (Binding.CmdT.setAlways Counter.Decrement) member _.StepSize with get() = base.Get() (Binding.OneWayT.id >> Binding.mapModel (fun m -> m.StepSize)) and set(v) = base.Set(v) (Binding.OneWayToSourceT.id >> Binding.mapMsg Counter.Msg.SetStepSize)
Create a function that accepts the app’s main window (to be created) and configures and starts the Elmish loop for the window with your
init
,update
andbindings
:open Elmish.WPF let main window = Program.mkSimple init update bindings |> Program.runElmishLoop window
Alternatively, use a statically-typed view model at the top level.
open Elmish.WPF let main window = Program.mkSimpleT init update CounterViewModel |> Program.runElmishLoop window
In the code above,
Program.runElmishLoop
will set the window’sDataContext
to the specified bindings and start the Elmish dispatch loop for the window.Create a WPF app project (using the Visual Studio template called
WPF App (.NET)
). This will be your entry point and contain the XAML views. Add a reference to the F# project, and make the following changes in thecsproj
file:- Currently, the core Elmish logs are only output to the console. If you want a console window for displaying Elmish logs, change
<OutputType>WinExe</OutputType>
to<OutputType>Exe</OutputType>
and add<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
. - If the project file starts with the now legacy
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
, change it to<Project Sdk="Microsoft.NET.Sdk">
- Change the target framework to match the one used in the F# project (e.g.
net5.0-windows
).
Make the following changes to
App.xaml.cs
to initialize Elmish when the app starts:public partial class App : Application { public App() { this.Activated += StartElmish; } private void StartElmish(object sender, EventArgs e) { this.Activated -= StartElmish; Program.main(MainWindow); } }
- Currently, the core Elmish logs are only output to the console. If you want a console window for displaying Elmish logs, change
Define your views and bindings in XAML:
<Window x:Class="MyNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding CounterValue}" /> <Button Command="{Binding Decrement}" Content="-" /> <Button Command="{Binding Increment}" Content="+" /> <TextBlock Text="{Binding StepSize}" /> <Slider Value="{Binding StepSize}" TickFrequency="1" Minimum="1" Maximum="10" /> </StackPanel> </Window>
Profit! 😃
Further resources:
- The Elmish.WPF tutorial provides information on general MVU/Elmish concepts and how they apply to Elmish.WPF, as well as the various Elmish.WPF bindings.
- The samples are complete, working mini-apps demonstrating selected aspects of Elmish.WPF.
- If you'd like to contribute, please read and follow the Contributor guidelines.
FAQ
Static views in MVU? Isn’t that just a half-baked solution that only exists due to a lack of better alternatives?
Not at all! 🙂
It’s true that static views aren’t as composable as dynamic views. It’s also true that at the time of writing, there are no solid, production-ready dynamic UI libraries for WPF (though there are no lack of half-finished attempts or proof-of-concepts: Elmish.WPF.Dynamic, Fabulous.WPF, Skylight, Uil). Heck, it’s even true that Elmish.WPF was originally created with static views due to the difficulty of creating a dynamic UI library, as described in issue #1.
However, Elmish.WPF’s static-view-based solution has several unique benefits:
- You can use your existing XAML and MVVM knowledge (that is, the best part of MVVM – the UI bindings – without having to deal with
NavigationService
s,ViewModelLocator
s, state synchronization,INotifyPropertyChanged
, etc.) - Huge mindshare – there are tons of relevant XAML and MVVM resources on the net which can help with the UI and data binding part if you get stuck
- Automatic support for all 3rd party WPF UI libraries like MaterialDesignInXamlToolkit, since it just uses XAML and bindings (support for 3rd party libraries is commonly a major pain point for dynamic UI solutions)
- You can use the XAML designer (including design-time data binding)
- Automatically puts all the power of WPF at your fingertips, whereas dynamic UI solutions have inherent limitations that are not easy to work around
In short, for WPF apps, a solution based on static XAML views is currently the way to go.
Do I have to use the project structure outlined above?
Not at all. The above example, as well as the samples, keep all non-UI code in a single project for simplicity, and all the XAML in a C# project for better tooling.
An alternative with a clearer separation of UI and core logic can be implemented by splitting the F# project into two projects:
- A core library containing the model definitions and
update
functions.- This library can include a reference to Elmish (e.g. for the
Cmd
module helpers), but not to Elmish.WPF, which depends on WPF and has a UI-centered API (specifying bindings). This will ensure your core logic (such as theupdate
function) is free from any UI concerns, and allow you to re-use the core library should you want to port your app to another Elmish-based solution (e.g. Fable.React).
- This library can include a reference to Elmish (e.g. for the
- An Elmish.WPF project that contains the
bindings
(orview
) function and the call toProgram.runElmishLoop
.- This project would reference the core library and
Elmish.WPF
.
- This project would reference the core library and
Another alternative is to turn the sample code on its head and have the F# project be a console app containing your entry point (with a call to Program.runWindow
) and referencing the C#/XAML project (instead of the other way around, as demonstrated above).
In general, you have a large amount of freedom in how you structure your solution and what kind of entry point you use.
How can I test commands? What is the CmdMsg pattern?
Since the commands (Cmd<Msg>
) returned by init
and update
are lists of functions, they are not particularly testable. A general pattern to get around this is to replace the commands with pure data that are transformed to the actual commands elsewhere:
- Create a
CmdMsg
union type with cases for each command you want to execute in the app. - Make
init
andupdate
returnmodel * CmdMsg list
instead ofmodel * Cmd<Msg>
. Sinceinit
andupdate
now return data, they are much easier to test. - Create a trivial/too-boring-to-test
cmdMsgToCmd
function that transforms aCmdMsg
to the correspondingCmd
. - Finally, create “normal” versions of
init
andupdate
that you can use when creatingProgram
. Elmish.WPF providesProgram.mkProgramWpfWithCmdMsg
that does this for you (but there’s no magic going on – it’s really easy to do yourself).
The FileDialogsCmdMsg sample demonstrates this approach. For more information, see the Fabulous documentation. For reference, here is the discussion that led to this pattern.
Can I use design-time view models?
Yes. Assuming you have a C# XAML and entry point project referencing the F# project, simply use ViewModel.designInstance
(e.g. in the F# project) to create a view model instance that your XAML can use at design-time:
module MyAssembly.DesignViewModels
let myVm = ViewModel.designInstance myModel myBindings
Then use the following attributes wherever you need a design-time VM:
<Window
...
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:MyAssembly;assembly=MyAssembly"
mc:Ignorable="d"
d:DataContext="{x:Static vm:DesignViewModels.myVm}">
When targeting legacy .NET Framework, “Project code” must be enabled in the XAML designer for this to work.
If you are using static view models, make sure that the View Model type is in a namespace and add a default constructor that passes a model into ViewModelArgs.simple
:
namespace ViewModels
type [<AllowNullLiteral>] AppViewModel (args) =
inherit ViewModelBase<AppModel, AppMsg>(args)
new() = AppViewModel(App.init () |> ViewModelArgs.simple)
Then use the following attributes just like you would in a normal C# MVVM project:
<Window
...
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:ViewModels.SubModelStatic;assembly=MyAssembly"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=vm:AppViewModel, IsDesignTimeCreatable=True}">
.NET Core 3 workaround
When targeting .NET Core 3, a bug in the XAML designer causes design-time data to not be displayed through DataContext
bindings. See this issue for details. One workaround is to add a d:DataContext
binding alongside your normal DataContext
binding. Another workaround is to change
<local:MyControl DataContext="{Binding Child}" />
to
<local:MyControl
DataContext="{Binding Child}"
d:DataContext="{Binding DataContext.Child,
RelativeSource={RelativeSource AncestorType=T}}" />
where T
is the type of the parent object that contains local:MyControl
(or a more distant ancestor, though there are issues with using Window
as the type).
Can I open new windows/dialogs?
Sure! Just use Binding.subModelWin
. It works like Binding.subModel
, but has a WindowState
wrapper around the returned model to control whether the window is closed, hidden, or visible. You can use both modal and non-modal windows/dialogs, and everything is a part of the Elmish core loop. Check out the NewWindow sample.
Note that if you use App.xaml
startup, you may want to set ShutdownMode="OnMainWindowClose"
in App.xaml
if that’s the desired behavior.
Can I bind to events and use behaviors?
Sure! Check out the EventBindingsAndBehaviors sample. Note that you have to install the NuGet package Microsoft.Xaml.Behaviors.Wpf
.
How can I control logging?
Elmish.WPF uses Microsoft.Extensions.Logging
. To see Elmish.WPF output in your favorite logging framework, use WpfProgram.withLogger
to pass an ILoggerFactory
:
WpfProgram.mkSimple init update bindings
|> WpfProgram.withLogger yourLoggerFactory
|> WpfProgram.runWindow window
For example, in Serilog, you need to install Serilog.Extensions.Logging and instantiate SerilogLoggerFactory
. The samples demonstrate this.
Elmish.WPF logs to these categories:
Elmish.WPF.Update
: Logs exceptions (Error level) and messages/models (Trace/Verbose level) duringupdate
.Elmish.WPF.Bindings
: Logs events related to bindings. Some logging is done at the Error level (e.g. developer errors such as duplicated binding names, using non-existent bindings in XAML, etc.), but otherwise it’s generally just Trace/Verbose for when you really want to see everything that’s happening (triggeringPropertyChanged
, WPF getting/setting bindings, etc.)Elmish.WPF.Performance
: Logs the performance of the functions you pass when creating bindings (get
,set
,map
,equals
, etc.) at the Trace/Verbose level. UseWpfProgram.withPerformanceLogThreshold
to set the minimum duration to log.
The specific method of controlling what Elmish.WPF logs depends on your logging framework. For Serilog you can use .MinimumLevel.Override(...)
to specify the minimum log level per category, like this:
myLoggerConfiguration
.MinimumLevel.Override("Elmish.WPF.Bindings", LogEventLevel.Verbose)
...
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net6.0-windows7.0 is compatible. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp3.1 is compatible. |
.NET Framework | net48 is compatible. net481 was computed. |
-
.NETCoreApp 3.1
- Elmish (>= 4.0.1 && <= 4.99.0)
- FSharp.Core (>= 6.0.5 && <= 99.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 6.0.1 && <= 99.0.0)
-
.NETFramework 4.8
- Elmish (>= 4.0.1 && <= 4.99.0)
- FSharp.Core (>= 6.0.5 && <= 99.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 6.0.1 && <= 99.0.0)
-
net6.0-windows7.0
- Elmish (>= 4.0.1 && <= 4.99.0)
- FSharp.Core (>= 6.0.5 && <= 99.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 6.0.1 && <= 99.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
4.0.0-beta-56 | 87 | 10/1/2024 |
4.0.0-beta-55 | 216 | 6/4/2024 |
4.0.0-beta-54 | 313 | 9/27/2023 |
4.0.0-beta-53 | 164 | 9/9/2023 |
4.0.0-beta-52 | 155 | 9/1/2023 |
4.0.0-beta-50 | 192 | 5/19/2023 |
4.0.0-beta-49 | 172 | 5/6/2023 |
4.0.0-beta-48 | 112 | 5/6/2023 |
4.0.0-beta-47 | 142 | 5/2/2023 |
4.0.0-beta-46 | 154 | 4/5/2023 |
4.0.0-beta-45 | 338 | 7/25/2022 |
4.0.0-beta-44 | 529 | 4/6/2022 |
4.0.0-beta-43 | 197 | 4/3/2022 |
4.0.0-beta-42 | 993 | 9/11/2021 |
4.0.0-beta-41 | 4,032 | 3/12/2021 |
4.0.0-beta-40 | 537 | 3/9/2021 |
4.0.0-beta-3 | 1,254 | 2/22/2021 |
4.0.0-beta-2 | 237 | 2/13/2021 |
4.0.0-beta-1 | 278 | 2/11/2021 |
3.5.8 | 2,575 | 3/31/2021 |
3.5.7 | 503 | 2/5/2021 |
3.5.6 | 3,939 | 5/21/2020 |
3.5.5 | 588 | 4/24/2020 |
3.5.4 | 532 | 4/16/2020 |
3.5.3 | 549 | 4/13/2020 |
3.5.2 | 52,193 | 10/26/2019 |
3.5.1 | 1,110 | 10/16/2019 |
3.5.0 | 692 | 10/2/2019 |
3.4.1 | 593 | 9/26/2019 |
3.4.0 | 579 | 9/26/2019 |
3.3.0 | 602 | 9/16/2019 |
3.2.1 | 886 | 8/22/2019 |
3.2.0 | 595 | 8/20/2019 |
3.1.0 | 1,290 | 6/4/2019 |
3.0.0 | 623 | 5/28/2019 |
2.0.0 | 1,065 | 4/23/2019 |
2.0.0-beta-9 | 613 | 3/23/2019 |
2.0.0-beta-8 | 853 | 1/28/2019 |
2.0.0-beta-7 | 613 | 12/9/2018 |
2.0.0-beta-6 | 609 | 12/1/2018 |
2.0.0-beta-5 | 943 | 10/21/2018 |
2.0.0-beta-4 | 633 | 10/13/2018 |
2.0.0-beta-3 | 865 | 9/28/2018 |
2.0.0-beta-2 | 636 | 9/12/2018 |
2.0.0-beta-11 | 470 | 4/17/2019 |
2.0.0-beta-10 | 470 | 4/15/2019 |
2.0.0-beta-1 | 693 | 9/1/2018 |
1.0.0-beta-7 | 4,318 | 12/5/2017 |
1.0.0-beta-6 | 750 | 11/17/2017 |
1.0.0-beta-5 | 738 | 11/8/2017 |
1.0.0-beta-4 | 907 | 7/12/2017 |
1.0.0-beta-3 | 813 | 7/6/2017 |
1.0.0-beta-2 | 768 | 6/29/2017 |
1.0.0-beta-1 | 791 | 6/22/2017 |
0.9.0-beta-9 | 778 | 6/12/2017 |