Friday, November 15, 2013

Getting Started with KSMVVM.WPF Part 2: Messaging

(This is part 2 of 2 in a series about getting started with KSMVVM.WPF)

At the end of Getting Started with KSMVVM.WPF, we successfully converted our SampleApplication to use ViewModels. However, one of our ViewModels still has UI-specific code in it. If we write and run automated ViewModel tests, testing FormViewModel.Submit will show a MessageBox. This is not good!

KSMVVM.WPF has a messaging component, and we'll use its BasicMessager class to move the call to MessageBox.Show out of FormViewModel.


Adding Messaging to FormViewModel

BasicMessenger is a very simple messaging class. You pass a String ID and an Action to BasicMessenger.Register, then you pass the same ID to BasicMessenger.Send. You can call BasicMessenger.Unregister (again, with the same ID you used before) to remove the registration from BasicMessenger. That's it!

It sounds simple, but we can use to to easily add messaging to FormViewModel.

Open FormViewModel.cs and add the following property:
public BasicMessenger Messenger { get; private set; }

Add the following line at the end of FormViewModel's constructor:
Messenger = new BasicMessenger();

Next, add the following constant to FormViewModel:
public const string SubmitFinishedId = "SubmitFinished";

Finally, replace the part of FormViewModel that sets the Submit command property with the following:

Submit = new BasicCommand(
    //Execute
    () =>
    {
        Messenger.Send(SubmitFinishedId);
        _nav.GoBack();
    });


(This replaces the 'show MessageBox' code with a call to Messenger.Send)

Adding Messaging to FormPage

It's now time to add messaging hooks to FormPage. It's a short, two-step process.

1. Add the Loaded event handler

Its code-behind should look like this:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    _viewModel.Messenger.Register(FormViewModel.SubmitFinishedId,
        () =>
        {
            string boxMessage = string.Format(CultureInfo.InvariantCulture,
                "Data submitted:\n{0} - {1}",
                _viewModel.Model.Name,
                _viewModel.Model.Amount);

            MessageBox.Show(boxMessage);
        });
}


2. Add the Unloaded event handler

You should unregister stuff on Unloaded that gets registered on Loaded. Just as a general rule.

The Unloaded event handler should look like this:

private void Page_Unloaded(object sender, RoutedEventArgs e)
{
    _viewModel.Messenger.Unregister(FormViewModel.SubmitFinishedId);
}


That's all there is to KSMVVM.WPF's messaging component. There probably won't be a third part of this tutorial series: KSMVVM.WPF is very simple.

No comments:

Post a Comment