Click here to Skip to main content
12,300,240 members (50,293 online)
Click here to Skip to main content
Add your own
alternative version

Stats

22.6K views
33 bookmarked
Posted

Using ReactiveUI for WinForms MVVM Design

, 4 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
A brief example showing how to use the Reactive UI framework to perform a separation of concerns using MVVM.

Introduction

In this article, we will look at an elegant way to separate the UI concerns of the presentation layer of a WinForms application from the application business logic using a MVVM (Model-View-ViewModel) pattern. In this way, Test-Driven-Development (TDD) of the application can be facilitated.

Background

While reading an article by Peter Vogel (see VSMagazine2014-05-01), I was reminded again of the difficulty WinForm application designers have working with modern design patterns. I have been searching for a long time for an easier way to accomplish what Brian Noyes appears to have accomplished with WinForms (see Composite Extensions for WinForms) without the contortions of using code borrowed from the Patterns and Practices Composite WPF Contrib library (http://compositewpfcontrib.codeplex.com/), which is difficult to follow and appears to have been abandoned (like so many things on the internet). However, the recent appearance of ReactiveUI 6.0 promises to improve the development of WinForms applications. ReactiveUI 6.0 is a Model-View-ViewModel framework that's used along with the Reactive Extensions library in constructing testable UIs.

Using the code

Let’s go through a brief example of using ReactiveUI to construct a WinForms application that uses the MVVM pattern. I will be using Visual Studio 2013 Express for Windows Desktop and the default WinForms template. Open up the main form created by the template and add the following controls:

  • Text label
  • Text box
  • OK button
  • StatusStrip Status string

Use the NuGet Package Manager under the Tools menu and add the reactiveui-winforms package to the solution. This package will add all the necessary references and components we will need.

At this point, since the view is partially constucted, we  construct the ViewModel that will process data and events. Lets set up properties with backing fields for the controls on the view and one command for the button.

//
// ViewModel example
//
namespace WinFormMVVM.ViewModels
{
	public class HomeViewModel : ReactiveUI.ReactiveObject
	{
		string ModelString;
		public string EnteredText
		{
			get { return ModelString; }
			set { this.RaiseAndSetIfChanged( ref ModelString, value);}
		}

		string statusString = "";
		public string Status
		{
			get{return statusString;}
			set{this.RaiseAndSetIfChanged(ref statusString,value);}
		}

		public ReactiveCommand<object> OKCmd { get; private set; }

		public HomeViewModel
		{
			var OKCmdObs = this.WhenAny(vm => vm.EnteredText, 
				s => !string.IsNullOrWhiteSpace(s.Value));
			OKCmd = ReactiveCommand.Create(OKCmdObs);
			OKCmd.Subscribe(_=> Status = EnteredText + " is saved.");
		}
	}
}

The ViewModel inherits from the ReactiveObject class. This class  grants your classes access to the RaiseAndSetIfChanged helper function. This conveniently wires up your properties to the INotifyPropertyChanged/IObservable interfaces, so in one step you have a class that can be data bound AND observed using Reactive Extensions.

In the constructor for the ViewModel we set up the conditions under which something happens, i.e. when the OK button is clicked. An IObservable object is returned from the WhenAny extension, which allows you to observe whenever one or more properties on an object have changed. We then Subscribe to the events of the ReactiveCommand, which will update the status message. Note that the ViewModel has no references to any UI elements, which allows us to perform testing without worrying about the particular UI technology used.

The astute reader will notice that at this point there is no link between the View and the ViewModel. Let's take care of that now that the ViewModel is built. Edit the View to inherit from the interface IViewFor<T>, where T is our ViewModel.

namespace WinFormMVVM
{
	public partial class HomeView : Form, IViewFor<HomeViewModel>
	{
		InitializeComponent();
		VM = new HomeViewModel();

		// Bind the view to the ReactiveUI viewmodel
		this.Bind(VM, x => x.EnteredText, x => x.textBoxMyInput.Text);
		this.Bind(VM, x => x.Status, x => x.toolStripMyStatusString.Text);
		this.BindCommand(VM, x => x.OKCmd, x => x.btnOK);
	}

	public HomeViewModel VM { get; set; }

	object IViewFor.ViewModel
	{
		get { return VM; }
		set { VM = (HomeViewModel)value; }
	}

	HomeViewModel IViewFor<HomeViewModel>.ViewModel
	{
		get { return VM; }
		set { VM = value; }
	}
}

 What I really like about using this framework is the availability of intellisense in writing the bindings between the UI elements and the VIewModel properties. The absence of "magic strings" typical in XAML or regular WinForm data bindings, that really makes code maintenance difficult, is especially welcome.

Points of Interest

The present state of the ReactiveUI framework is not documented as well as might be hoped for. It took a fair amount of time to ferret out meaning from outdated examples and code breaking changes. I hope this example will serve to inspire others to dig into ReactiveUI and provide more examples and better documentation.

History

2014-Jul-29 Initial Draft

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

gardner9032
Software Developer (Senior) AcmeSource
United States United States
You're not a real programmer until you have toggled binary into a PDP-11 and memorized Z80 op codes so you can program without an assembler. I've spilled more punch card decks than coffee cups and still managed to run light without overbyte into today's world. An eclectic programmer with experience in C, C#, Python, LabView, VB, SQL, and many other things, I happen to believe HTML5 and JavaScript are boring.

You may also be interested in...

Comments and Discussions

 
PraiseGood Pin
Member 1216516424-Nov-15 18:47
memberMember 1216516424-Nov-15 18:47 
GeneralRe: Good Pin
gardner903225-Nov-15 8:22
membergardner903225-Nov-15 8:22 
QuestionBindCommand does not compile in VB version of project Pin
Reader Man San8-Jun-15 12:48
memberReader Man San8-Jun-15 12:48 
AnswerRe: BindCommand does not compile in VB version of project Pin
gardner903229-Jul-15 5:52
membergardner903229-Jul-15 5:52 
GeneralRe: BindCommand does not compile in VB version of project Pin
Reader Man San1-Aug-15 10:32
professionalReader Man San1-Aug-15 10:32 
Questionlinux and Mono Pin
Sam Gerené10-Dec-14 4:37
memberSam Gerené10-Dec-14 4:37 
AnswerRe: linux and Mono Pin
gardner903210-Dec-14 15:35
membergardner903210-Dec-14 15:35 
GeneralC# Solution in github Pin
nrodriguez20143-Dec-14 12:39
membernrodriguez20143-Dec-14 12:39 
GeneralRe: C# Solution in github Pin
gardner90324-Dec-14 3:18
membergardner90324-Dec-14 3:18 
GeneralRe: C# Solution in github Pin
nrodriguez20145-Dec-14 6:28
membernrodriguez20145-Dec-14 6:28 
QuestionProblem implementing the partial class HomeView Pin
nrodriguez20143-Dec-14 9:21
membernrodriguez20143-Dec-14 9:21 
GeneralMy vote of 3 Pin
BAIJUMAX17-Sep-14 21:23
memberBAIJUMAX17-Sep-14 21:23 
GeneralGreat article. Pin
ahmedshuhel4-Aug-14 23:15
memberahmedshuhel4-Aug-14 23:15 
QuestionIs it free for commercial use ?? Pin
Tridip Bhattacharjee4-Aug-14 21:33
memberTridip Bhattacharjee4-Aug-14 21:33 
AnswerRe: Is it free for commercial use ?? Pin
ahmedshuhel4-Aug-14 23:00
memberahmedshuhel4-Aug-14 23:00 
GeneralMy vote of 5 Pin
taras_b4-Aug-14 20:16
membertaras_b4-Aug-14 20:16 
GeneralRe: My vote of 5 Pin
Some D00d6-Aug-14 8:45
memberSome D00d6-Aug-14 8:45 
GeneralMy vote of 1 Pin
ashwini37374-Aug-14 19:42
memberashwini37374-Aug-14 19:42 
GeneralRe: My vote of 1 Pin
taras_b4-Aug-14 20:15
membertaras_b4-Aug-14 20:15 
GeneralRe: My vote of 1 Pin
sam.hill5-Aug-14 4:49
membersam.hill5-Aug-14 4:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160525.2 | Last Updated 5 Aug 2014
Article Copyright 2014 by gardner9032
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid