Monday, June 29, 2009

WPF and MVVM - A Look at the Microsoft Toolkit, Part 2

In my last post of this series, I promised to go over the contents and purpose of the several files included in the application project generated by the Microsoft WPF-MVVM project template. Here, again, is a picture of the initial contents as displayed in the Visual Studio Solution Explorer:

Figure 1. MyWpfApp Solution


Recall that the only files in the project folder itself are App.xaml and its code-behind file App.xaml.cs. These files are responsible for “kicking off” the application. Let’s begin by looking at App.xaml:

Figure 2. App.Xaml


The critical element here is the Startup attribute of the Application tag. Its value says, “Invoke the code found in the OnStartup event handler." This event handler is found in the code-behind file App.xaml.cs:

Figure 3. App.xaml.cs
Here, a main window for the application is created (MainView), the data source for its controls is established (MainViewModel), and the window is displayed. Where did MainView and MainViewModel come from? Referring again to Figure 1, notice that the WPF-MVVM template provides initial versions of these classes for you in the Views and the ViewModels folders, respectively.

Looking at the XAML for MainView, we find an initial File menu with an Exit menu item that is linked to ‘ExitCommand’, and an empty grid:
Figure 4. MainView.xaml


However, there is no code-behind except for a constructor that invokes an InitializeComponent method to paint the window controls on your display:
Figure 5. MainView.xaml.cs

Where is ExitCommand defined? Recall that the OnStartup event handler in App.xaml.cs established MainViewModel as the primary data source (i.e., DataContext) for MainView. Here we find the mysterious ExitCommand:
Figure 6. MainViewModel.cs

Notice that it is a read-only property of type ICommand. The ICommand interface, which must be implemented in all commands that interact with WPF, exposes two methods and an event. The first method, Execute, defines the method that is called when the command is invoked. The signature for this method must agree with that of the Action delegate:

public delegate void Action() or
public delegate void Action( T parameter )

The second method, CanExecute, defines the method that determines whether or not the command can execute in its current state. Its signature must agree with that of the Predicate delegate:

public delegate bool Predicate() or
public delegate bool Predicate( T parameter )

The event, CanExecuteChanged, occurs when changes that affect whether or not the command should execute occur. The WPF-MVVM template provides a DelegateCommand class, located in the Commands folder, that implements this interface. In most situations you will be able to use this class “as is” to define additional commands in MainViewModel or in any other view model class you may need to create.

The other class in the Commands folder, CommandReference, provides a Command dependency property, so you can more easily bind a keyboard sequence – e.g., Control + X – to a command. A discussion of dependency properties is beyond the scope of this blog entry. Just bear in mind that all bindable control properties are dependency properties.

You will no doubt note that in MainViewModel, only the Execute method – aptly named Exit – is defined. MainViewModel relies on the default implementation of CanExecute provided by DelegateCommand, which merely returns ‘true’. Neither does it subscribe to the CanExecuteChanged event, for which, again DelegateCommand provides a default handler implementation.

The other mystery found in the MainViewModel class definition is the fact that it is a sub-class of ViewModelBase. This base class implements the INotifyPropertyChanged interface, which consists of a single event – PropertyChanged. It also provides a handler for that event:
Figure 7. ViewModelBase.cs


WPF relies on the INotifyPropertyChanged event to establish proper communication between a view’s control properties and the data source for those properties. Implementing this interface in the data source class enables WPF to update the control property when its defined data source property changes, and vice versa. Since most view model classes are involved in this process, having ViewModelBase as a base class facilitates this effort.

That’s about it for an overview of the application project generated by the WPF-MVVM template. However, as you may recall, this template also gives you the option of generating a test project to go along with the application. If you refer back to Figure 1, you will notice that a single test class, MainViewModelTest, is generated. Within that class a single test method is generated. This method provides a stub for testing the MainViewModel constructor.

One of the primary advantages of adopting the MVVM pattern when developing a WPF application is that it enables you to test all of your code, including command execution, in a manner that is independent of the application UI. If you adopt this template, I would suggest that you define folders in the test project that correspond to the folders in the application project, and that you create one test class per application class.

With this overview behind us, we will proceed with the development of the Investment Tracker application in the next post.

Previous posts in this series:

Tuesday, June 23, 2009

WPF and MVVM - A Look at the Microsoft Toolkit, Part 1

You may recall from my last post, if you've read it, that I decided to use an adaptation of the Microsoft WPF MVVM Toolkit for the Investment Tracker application I'm developing. Before we dive into the application, we should first explore what the toolkit provides.

The toolkit comes with a project template, a sample application, and two white papers. The first paper provides a brief description of the MVVM pattern. The second paper provides step-by-step instructions for developing the sample application yourself. While I would not consider the application to be "complete," it does provide an excellent initial look at how to use the template and how to implement the MVVM pattern in a WPF application.

First, let's look at the template. Suppose, you want to develop an application called MyWpfApp. From Visual Studio, you would select from the menu: FileNewProject. This action, of course, brings up the New Project dialog. In the dialog, select, in the left pane, project type Visual C#Windows. Then, in the right pane, select the WPF Model-View Application template. Finally, in the first textbox of the lower portion of the dialog, name your project MyWpfApp:



After you click the OK button, you are asked, in another dialog, whether or not you want to create a test project:


After you click OK, a solution with a WPF/MVVM project (hereafter called the main project) and a test project is set up for you:



Notice that the only files in the main project folder itself are app.xaml and its code-behind file app.xaml.cs. Sub-folders are defined which, except for one, correspond to the different application "layers" associated with the MVVM pattern: Models, Views, and ViewModels. A folder that you might not have expected is the Commands folder. The Views, ViewModels, and Commands folders are populated with an initial set of files which may be used in developing your application. We will examine the contents and purpose of these files in the next post.

Previous posts in this series:

WPF and MVVM - Intro

WPF and MVVM - Orientation




Wednesday, June 10, 2009

WPF and MVVM - Orientation

It's been a while since my first post on this topic. Life is busy, and it's hard to fit in blogging.

In what time I have available I've been researching how to best achieve the separation of tasks described in the first post. There are quite a few blog entries out on the web, most of which really don't work except in specific cases, which, or course, the author presents. There are, though, several very good posts and two Microsoft sites that you may be interested in.

Joshua Smith has an excellent article and accompanying code example on MSDN: WPF Apps With The Model-View-ViewModel Design Pattern. In this article he introduces a concept which he calls the Relay Command.

Kent Boogaart has written a good series of articles. The final one in the series is MVVM Infrastructure: ActiveAware Command. The article contains links to the three prior articles in the series.

If you need to develop a large and/or complex WPF application, you might be interested in Microsoft's Prism - a composite application library. Check out Patterns & Practices: Composite WPF and Silverlight.

For smaller applications, Microsoft has a WPF MVVM Toolkit: WPF Toolkit - March 2009 Release.

In the end, and after a bit of experimentation, I decided to use an adaptation of the template that comes with the Microsoft toolkit. The template creates a solution with a single project with separate folders for the different segments of the MVVM pattern. I would have preferred separate projects in place of the folders, so I gave that a try, reworking the sample application that comes with the toolkit. It worked, so that's what I've decided to use in developing the Investment Tracking application.


Previous entries in this series:

WPF and MVVM - Intro