Tag Archives: viewmodel

No Events: ReactiveUI Windows Forms MVVM-Style

Review

designed using http://viperneo.github.io/winforms-modernui/

This is the next post in the series, looking first at Reactive Extensions (RX) to simplify writing Windows Forms UI logic, then using a viewmodel shared between a WPF gui implementation and a rewritten WinForms version using ReactiveUI, stopping at a short article on testing the viewmodels.

passedtest

ReactiveUI News

ReactiveUI API has been quite volatile for the last year, and this series is in need of an update[0. See ReactiveUI Design Guidelines]. A CodeProject author gardner9032 published a nice teaser article, showing the ReactiveUI mechanism for writing simplified Viewmodel-View bindings [1. see article @CodeProject], which serves as primary trigger for this post.

There’s plenty of news and updated articles on Paul Betts’ log, providing a good resource for updates on the API. Phil Haack’s blog is also a superb resource for explanations and commentaries on the use of ReactiveUI in real-world applications.

The ReactiveUI project is quite active, as the community seems to have grokked the jist of it, while the list of supported platforms has become more than convincing.

Getting rid of events

The enabling feature of ReactiveUI is writing declarative UI glue code, and if the viewmodels are based on Reactive Extensions, then declarative C# style can be used throughout the project. The previous ReactiveUI Windows Forms examples converted an event sequence into an observable sequence of values. In this example, that will be accomplished conveniently by the ReactiveUI WinForms lbrary. The viewmodels also contained some imperative code. For this article, the viewmodels will not be reused from the previous articles, but written from scratch.

ViewModel

s. code

The viewmodel’s task is the same: something is ticking in the background, while words are counted in the input text asynchronously, and the calculation is throttled to 0.5 seconds. The viewmodel boilerplate is simplified using ReactiveUI.ReactiveObject.

Output (read-only) properties

The ReactiveUI-way of creating output properties is through ObservableAsPropertyHelper.

private readonly ObservableAsPropertyHelper<string> backgroundTicker;
public string BackgroundTicker
{
    get
    {
        return backgroundTicker.Value;
    }
    //...
}

The constructor of the viewmodel receives an IScheduler for scheduling on the correct thread, and an IObservable, which will be a stream of input from the view. Observe the ToProperty helper:

public MyViewModel(IScheduler scheduler, IObservable<string> input)
{
    Observable.Interval(TimeSpan.FromSeconds(1))
        .ObserveOn(scheduler)
        .Select(_ => DateTime.Now.ToLongTimeString())
        .ToProperty(this, x => x.BackgroundTicker, out backgroundTicker);
    //...
}

Word counting logic is implemented in a similar fashion by transforming the incoming stream of strings.

View

s. code

To remove yet more boilerplate code, WinForms Form specialization implements the ReactiveUI.IViewFor interface. This allows for largely simplified run-time and compile-time checked bindings, avoiding using strings for property names. The implementation is straightforward, and pays off once the views become more complex than this example:

IViewFor

public MyViewModel VM { get; private set; }

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

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

Bindings

None of the controls in the designed WinForm have wired events or bindings set from the designer. The glue code is reduced to instantiating the viewmodel …

VM = new MyViewModel(
    new System.Reactive.Concurrency.ControlScheduler(this),
    this.WhenAnyValue(x => x.inputBox.Text)
);

… and declaring the bindings[2. The ReactiveUI WinForms implementation seems not to support fully read-only fields using default bindings yet, hence an empty setter in the viewmodel] [3. The scheduler is from Windows Forms helpers].

this.Bind(VM, x => x.BackgroundTicker, x => x.tickerBox.Text);
this.Bind(VM, x => x.WordCount, x => x.wordCountBox.Text);

Source

@github

The WPF + ReactiveUI Refactored Version of the Responsive UI Hello World

Overview

To recapitulate, the first article in the series used Reactive Extensions (Rx) directly in Windows Forms UI logic to implement a UI with a simulated background calculation, which delivered a timestamp each second. The rest of the application was an input text box, for which, when the user inputs the text, the word count is calculated asynchronously and posted into another read-only text box.

The second article introduced a WPF version of the same UI with a viewmodel that implements the INotifyPropertyChanged interface and supplies the ticker text and the word count as bindable properties. The text being input was delivered to the viewmodel via an event converted to an observable sequence, which was used to update the TextInput property of the viewmodel. The WordCount was updated from the setter of TextInput.

The third article recreated the WPF implementation in WinForms using the same viewmodel, which is shared between the two projects. The third UI implementation introduced throttling of the TextInput changes to 0.3 seconds so that the word count is updated only when the user pauses for at least a third of a second to take a look at the result.

The Refactored WPF Version

In this article, the WPF UI is further refactored, so that the concerns are separated further. These are organized as follows:

Create a sequence of some calculation results

These are timestamps in this case, implemented as an object, providing an IObservable<string> property Ticker:

public class BackgroundTicker
{
    public IObservable<string> Ticker
    {
        get
        {
            return Observable
                .Interval(TimeSpan.FromSeconds(1))
                .Select(_ => DateTime.Now.ToLongTimeString());
        }
    }
}

The observable sequence is active, delivering a value every second.

Count words in text asynchronously and provide another property calculated in the background

This viewmodel is finally implemented using ReactiveUI:

public class WordCounterModel : ReactiveObject

The word count and the input text are ReactiveUI boilerplate:

string _TextInput;
public string TextInput
{
    get { return _TextInput; }
    set { this.RaiseAndSetIfChanged(ref _TextInput, value); }
}

ObservableAsPropertyHelper<int> _WordCount;
public int WordCount
{
    get { return _WordCount.Value; }
}

The value sequence of the background ticker is injected at construction time using its observable member. The word count and the background ticker properties are implemented using an ObservableAsPropertyHelper.
The results of the background ticker are exposed via a property:

ObservableAsPropertyHelper<string> _BackgroundTicker;
public string BackgroundTicker
{
    get { return _BackgroundTicker.Value; }
}

the helper is initialized from the constructor-supplied observable:

someBackgroundTicker
    .ToProperty(this, ticker => ticker.BackgroundTicker, out _BackgroundTicker);

And finally, the word count logic is implemented as an output property, transforming the sequence of strings into a sequence of integers:

this.WhenAnyValue(x => x.TextInput)
    .Where(x => !string.IsNullOrWhiteSpace(x))
    .Select(x => x
        .Split()
        .Where(word => !string.IsNullOrWhiteSpace(word))
        .Count())
    .ToProperty(this, vm => vm.WordCount, out _WordCount);

The throttling can be removed from the viewmodel, as the WPF 4.5 has a Delay binding property, which can be used for the same purpose on the view side, freeing the viewmodel from that concern.

Provide a Graphical UI

Now let’s look at the view. The event subscription is gone and data binding is implemented in XAML declaratively. The DataContext of the main window is initialized with an instance of the viewmodel, which is initialized with an observable from an instance of a background ticker:

ViewModels.BackgroundTicker Ticker=new ViewModels.BackgroundTicker();
ViewModels.WordCounterModel VM = new ViewModels.WordCounterModel(Ticker.Ticker);
DataContext = VM;

This instantiation can be definitely made in XAML as well, nullifying the amount of C# code for the view, as for example in the following article.

The background ticker and the word count are now bound one-way and marked asynchronous.

<TextBox ... Text="{Binding BackgroundTicker,IsAsync=True,Mode=OneWay}"></TextBox>
<TextBox ... Text="{Binding WordCount,IsAsync=True,Mode=OneWay}"></TextBox>

And finally, the binding of the input text is configured in XAML to be throttled to 300 milliseconds and bind on PropertyChanged events of the Text property of the text box:

<TextBox ... Text="{Binding TextInput, UpdateSourceTrigger=PropertyChanged, Delay=300}"></TextBox>

Source Code

https://github.com/d-led/reactiveexamples

The WPF Version of the Responsive UI Hello World

What is lacking in the first version of the hello world example is the separation of UI and application logic. A refactored WinForms version may be the topic of a future post.

The next step in the discovery of Rx is to create a similar software using WPF. The details can be viewed in the source code, so let’s concentrate on the peculiarities. In this version, pure Rx will be used without ReactiveUI.

wpf version of ui hello world

WPF brings a possibility of total separation of UI, UI logic and application logic. A part of the application can be implemented by bindings to a viewmodel. The viewmodel has to implement the INotifyPropertyChanged interface. We’ll choose the implementation from here for the moment.

The viewmodel is defined as follows, omitting the INotifyPropertyChanged details:

public class MyViewModel : INotifyPropertyChanged
{
    //http://msdn.microsoft.com/en-us/library/ms229614.aspx details ...

    string _CurrentTime;
    public string CurrentTime
    {
        get { return _CurrentTime; }
        private set
        {
            if (value != _CurrentTime)
            {
                _CurrentTime = value;
                NotifyPropertyChanged();
            }
        }
    }

    string _TextInput;
    public string TextInput
    {
        get { return _TextInput; }
        set
        {
            if (value != _TextInput)
            {
                _TextInput = value;
                NotifyPropertyChanged();
                UpdateWordCount();
            }
        }
    }

    private void UpdateWordCount()
    {
        WordCount = TextInput.Split()
            .DefaultIfEmpty()
            .Where(s => s.Trim().Length > 0)
            .Count();
    }

    int _WordCount;
    public int WordCount
    {
        get { return _WordCount; }
        private set
        {
            if (value != _WordCount)
            {
                _WordCount = value;
                NotifyPropertyChanged();
            }
        }
    }

    public MyViewModel()
    {
        Observable.Interval(TimeSpan.FromSeconds(1))
            .Subscribe(_ => CurrentTime = DateTime.Now.ToLongTimeString());
    }
}

By using the separation the application logic becomes testable without building a UI, as the viewmodel is not dependent on System.Windows*.

The word count and the current time field can be bound to the controls by using the standard binding mechanism:

<TextBox ... Text="{Binding CurrentTime}"></TextBox>
<TextBox ... Text="{Binding WordCount}"></TextBox>

However, if we want the word count to be updated on every text change and not after focus change, we’ll have to use the TextChanged of the third text box to update the viewmodel. The update of the word count is currently implemented in the setter for the TextInput property on line 29. Using ReactiveUI this will change as well.

The configuration of the UI by code-behind looks as follows:

ViewModels.MyViewModel VM = new ViewModels.MyViewModel();
DataContext = VM;
var textChanged = Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
    handler => handler.Invoke,
    h => textBox3.TextChanged += h,
    h => textBox3.TextChanged -= h);
textChanged.Subscribe(_ => VM.TextInput = textBox3.Text);

Compared to the first WinForms version it has two responsibilities less – the current time update logic and the word count logic, which is now in the viewmodel.

As the next step, the implementation of the viewmodel should be further simplified.

Source code can be found here.