CODE Pathway Gateway
   Almost free!  One day of FREE VFP to WPF evaluation of your FoxPro app ONSITE
   Free!  Read the foreword to Les' new book (available here)...
Skip Navigation Links

Add-Edit-Delete forms in WPF with MVVM and IdeaBlade DevForce 2010

A minimalist approach to Add-Edit-Delete forms with WPF and MVVM

Les Pinter

You're one hour away from building Add-Edit-Delete forms in WPF using MVVM

Coding time: 60 minutes.   

Jump to: 

 Introduction   The MVVM Framework   The Model   The Form - er, View   The ViewModel   Unit Testing   Conclusion 



Windows Presentation Foundation (WPF) is Microsoft's replacement for the WinForms designer. It's a huge improvement over what we've been using for the past 20 or so years. It uses vector graphics to render the text-based XAML code that you build in the designer into screens that can do anything you've ever seen on a video display.

But WPF isn't just for designing beautiful user interfaces. It also permits unit testing of your code, which is about a hundred times faster than launching the app and drilling down to the screen you were just working on. This involves using a methodology called Model-View-ViewModel (MVVM), in which you move all code-behind to another class, called a ViewModel. You can include tests in the ViewModel classes that can be run without launching the corresponding forms. Add to that the ability to easily discover that the change that you just made broke some code elsewhere in your app, and MVVM is the inexpensive way to build desktop applications. And by the way, WPF apps will always cost less to build, and run faster, than HTML5 or any other kind of browser-based nonsense. So don't believe everything you hear.

However, MVVM is not easy. Many developers have read articles on MVVM and simply decided that it wasn't worth the trouble. Who would exchange the devil you do know for the devil you don't know?

The purpose of this article is to demonstrate a minimalist approach to MVVM that you can master and use in your next application. It doesn't have all of the bells and whistles that MVVM permits, but it's straightforward, and you absolutely can master it today. So let's get started.

The MVVM framework

MVVM is the acronym for Model-View-ViewModel. A View is a form; a ViewModel is a class that holds the code that used to go in the form's CodeBehind file; and a Model is a class that retrieves and stores your data, and (most importantly) exposes it to your View (form) via WPF Binding. So the data goes from the Model into public properties in the ViewModel. Your View then uses binding to retrieve the data that's now in the ViewModel object, and to send changes back to it. The ViewModel then calls methods on the Model to store the data. The methods to retrieve and store data are in the ViewModel, not in the form - er, View. They're connected using something called Commanding, which requires about 4 lines of code per CommandButton.

This means that you can run unit tests against the ViewModel without launching the View, because the code that gets data and handles events like button-clicks isn't in the View's CodeBehind. And that's the whole point. You don't need to launch the form to exercise your code. So a testbench like NUnit can test your code and validate it without running the program. And did I mention that it's fast?

When I first heard about MVVM, I immediately sat down to write an Add/Edit/Delete form, the heart of all database applications. I read dozens of articles about MVVM, and surprisingly, none of them got me to the point of a working application. They went on and on about the wonders of MVVM, but they didn't show me how to add or delete a record. They reminded me of the super salesman whose new bride left him the morning after their first honeymoon night, because he sat at the end of the bed all night telling her how great it was going to be. Just get on with it, okay?

So let's get on with it.

In VS 2010, select File, New, New Project, and select WPF Application, designating a location that you'll be able to find easily later. Create a new project called AddEditDeleteProspects of type WPF Application. You'll see the following project in the Solution Explorer:

You'll probably want to use MainWindow as a splash screen and to display your main menu. You probably should change the name by renaming it, and I've done so, changing the file name to frmStartup. Note that if you rename it, you'll have to edit App.xaml and change the StartUri to the new .xaml file name - it's not automatic. Note further that even though you change the file names, internally the class name and its constructor name are still MainWindow. So, if you also change their names internally, be sure to do so both in the .xaml and in the .xaml.cs files.

The next steps will be to add a model to describe each of the tables in your database, and then to add one View and one ViewModel for each of the tables that require a user maintenance form. You can share a ViewModel among several forms, and sometimes that's appropriate; but usually there will be exactly one ViewModel per View. A ViewModel is a class that interacts with the View, and a Model is a class that represents your data. You write the ViewModels, but IdeaBlade Devforce writes the Models. More on that later.

But before we add our Model, there's one class that we'll need; it's called CommandMap.cs. It's available in the download for this article. Register (it's free), and when you reload the article, the 'Log in or register' link will instead be a download the source code link. In the download, you'll find this file. This little class makes commanding, the process of connecting the click events of your commandbuttons (and other events) to code in the ViewModel, very easy. If I didn't include it, I'd have to go into a lengthy explanation about commanding, and that's usually where readers' eyes start to glaze over. Instead, you'll add three lines of code in each ViewModel, then add one more, plus the code for the method to execute when the button is clicked, for each command. That's simpler.

Copy CommandMap.cs into your project, then click on the Show All Files icon at the top of the Solution Explorer, highlight the new file, and then right click on it and select Include in Project from the resulting context menu. Look at the code if you want to, but it's not necessary, except to discover that the internal namespace is CommandUtilities, which you'll be using in your ViewModels. But first, let's add a Model.

The Model

I have a table called Prospects that's used in this project. In the download for the article, there's a SQL script that creates a database called Tests, then adds and populates a table called Prospects. I used SQL 2008 R2, which does constraints a little differently. The version shown below will also work with earlier versions of MS SQL.

The choice of a GUID (a Globally Unique IDentifier) is a good one, because it simplifies the insertion of a new record key. If you use an integer identity column, in a multiuser environment you're faced with reserving the next sequential number to be set aside while the user finishes entering the data for the new prospect, and then either inserting the record or canceling it. Usually a temporary negative integer is used, but it's a hassle no matter how you deal with it. Guids are the simplest way to supply a unique key. NewID() is SQL's Guid generator, and the database table creation statement shown above uses it; but in our case, we'll just assign one in code, as you'll see in Listing 5.

Before we go any further, at the end of this article I'm going to build a form to search for a particular Prospect and display it in the Prospects form. To do this, I've declared a public static Guid field in App.xaml.cs to hold the user-selected Prospect ID in frmFindAProspect, and then use it to retrieve the corresponding prospect when I return from the search form. Add just one line in App.xaml.cs, just after the class declaration statement (the "?" means that the field can be null):

public partial class App : Application
  public static Guid? ID = new Guid();   // <== add this line...
Note: You can also create a partial class for the Prospects entity, and then add this code in the Create method, and it will happen every time you create a new record. But this is an article about MVVM, not about IdeaBlade DevForce, which can do more than you'll probably ever need or even want to know about.

Now, if you haven't already done so, go to and download the demonstration version of their DevForce 2010 ORM tool. It doesn't time out. It will only support up to ten tables, which makes it useful only for learning purposes. If you have an application with hundreds of tables, the value of the application will justify the grand or so that it costs. But the learning version is free.

To see DevForce in action, right click on your project in the Solution Explorer and select Add, New Item from the context menu. Up in the Search Installed Templates box, type ADO. You'll see just a few selections (Fig. 2).

Pick the first one, ADO.NET Entity Data Model. Name it DataModel at the lower left of the screen and click on Add.

You'll be asked if you want to generate the model from the database, and you absolutely do (Fig. 3)

You'll be asked to either select a connection to the Tests database or to create a new one. The connection string that it creates is in entity-framework format, so it might look a little strange: (Fig. 4):

Next, you'll pick your table or tables and/or views and/or stored procedures. We just have one table, Prospects, so check it and click Ok (Fig. 5)

If you look at the output window, you'll see that it says something about code generation. That's what the ORM tool does, and it's fast. I've seen it generate a hundred thousand lines of code in sixty seconds. You don't touch this code. If you need to add something else to one or more tables, there's an app for that; more on that later.

Your Project in the Solution Explorer will now look like Fig. 7:

The highlighted files represent the Model of the data. The .edmx file contains the map of the table(s) in the Model; the .tt file points to the domain model template use by the IdeaBlade ORM tool to generate the code; and the .cs file contains the generated code, partly shown below in Listing 2:

There are a half-dozen classes in this generated code, but two of them are most important to us:

  • An EntityManager class called "TestEntities" that you use to get and save data; this class contains an EntityQuery called Prospects that can be used to return an ObservableCollection of Prospect entities;
  • The Prospect class that holds a prospect table row; for each column in the table there's a corresponding public property with property change notification built in. This is important for WPF, as we'll see shortly.

Those constructs are the scaffolding that we'll use to build our application.

The View

Back in frmStartup, I added one line to the <Window declaration at the top of the file:


I've also added a menu with the following structure:

File    Tables
  Exit    Prospects

We need to add event handlers for the Exit and Prospects MenuItems. Since their names will be used to generate event names, add "Name=" clauses to each. I used Name=mnuExit and Name=mnuProspects respectively. Now, select the Exit MenuItem, open the Properties Window using F4, select the Events tab (the one with the little lightning bolt icon), and double click on the Click event. In the resulting mnuExit_Click event handler method, add this:


But before we write the code to launch the Prospects form, we need to create said form. The WPF form designer is, to say the least, a little different from the WinForms designer. Every traditional developer I've ever worked with to build their first WPF form has asked the same question: "Why isn't the layout toolbar enabled?" That little question actually sheds a lot of light on the WPF paradigm.

In WPF, you use containers to align and line up controls. For example, if you want to stack five controls left to right, you use a stackpanel. You usually start with a grid, which has nothing to do with datagrids or gridviews or datagridviews. In WPF, a grid is just a rectangle. You can add row and column dividers, and then position a control within a particular "cell" of this grid by supplying coordinates, e.g. <TextBox Grid.Row="2", Grid.Column="4" />. A StackPanel stacks with either a vertical or horizontal orientation. A UniformGrid spaces things equidistantly. A Canvas is pretty much what you're used to working with in WinForms, and just to give you a flavor of this brave new world, it's absolutely the lamest of the bunch.

Containers are meant to be nested, so if you end up with a stackpanel within a grid within another grid within a stackpanel, that's probably just about right; I've had containers nested eight deep. That's why you don't have a Left and a Top setting for every control. There is, however, a Margin attribute, with Left, Top, Right and Bottom spacing parameters that occasionally comes in handy. I have a couple of articles coming up on xaml design, and I hope to convince you that it's actually pretty easy to use, even without using Blend. For now, though, try just using containers and the judicious application of Margin, Padding, VerticalAlignment and HorizontalAlignment, and that's usually enough.

In the Solution Explorer, highlight the project name, right click to open the context menu, and select Add, New Item, Window. Enter frmProspects as the file name. The Designer will open the new window (form) in a Designer window. Add the xaml shown in Listing 3:

To spice up the form's appearance, I've added a few styles to my App.xaml, as shown below in Listing 4:

The use of the StaticResources BG, TC and FF isn't required, but it makes assigning the same attributes (a color or a font) to several styles a lot easier.

The form is shown below in Fig. 8:

Now that you have a Prospects form, you can return to frmStartup.xaml, select mnuProspects, open the Properties Window, select the Events tab and double click on the Click event, and then add this code to the resulting mnuProspects_Click event handler:

   frmProspects fP = new frmProspects(); fP.Show();  // or fP.ShowDialog();

Press F5 to run the application and launch the window.

At this point, the Window contains no references to the data, and the code-behind consists of exactly one line of code: InitializeComponent; That's where the ViewModel comes in.

The ViewModel

For each View you'll create a ViewModel. The ViewModel is a class that's instantiated in the Load event of the corresponding form - er, View. Sorry, it's a hard habit to break. As soon as the ViewModel object is created, it's assigned to the DataContext of the View. Thereafter, any Binding reference is assumed to be a reference to a public property in the ViewModel. So, for example, if we have a prospect property that contains the currently selected record from the Prospects table, a binding to FirstName in a View control will look for it in the public property prospect in the ViewModel object, or in a public Model object inside the ViewModel. These properties must be public, because binding uses reflection to find them, and they have to be public, and they have to be properties - that is, they have to have accessors - a getter and a setter.

The values stored in public properties may change during program execution. If they do, the ViewModel class needs to implement the IPropertyChangeNotification interface, so that you can RaisePropertyChanged(PropertyName) to let the View know that it needs to refresh the data in the corresponding binding. To do that, you add : INotifyPropertyChanged at the end of the ViewModel Class declaration, and add the two boldfaced lines of code at the end of the ViewModel class as shown in listing 5. Then, include RaisePropertyChanged("PropertyName") as the last line in the getter of each property. I've hidden an undocumeted Easter Egg in the app's code to demonstrate it. It's hidden in plain sight...

In order to link ViewModel methods to events (particularly the Button Click event) in your View, you need to implement the ICommand interface. That's what CommandUtilities.cs is for. It gives you an easy way to add command delegates (sorry, that's what they're called) to your code and attach them to a particular button. You can either click on a button to execute the corresponding command, or you can just call the method in a TestFixture or from another method in your code. And, if you write a second method that returns true if the button should be enabled, or false if it should be disabled, you can pass it to the Commands constructor as the second (optional) parameter to automate that aspect of button control. See the Delete command for an example.

That's a lot of explanation, but if you study the code in Listing 5 using the line number references in the explanations that follow it, I think you'll find that most things are harder to explain than they are to do. Both binding and commanding generally take just a couple of lines of code.

Right click on the project name in the Solution Explorer and select Add, Class from the context menu. Assign the name frmProspects_VM, as shown in Fig. 9:

Then, add the code shown below in Listing 5:

I definitely have some 'splaining to do, so let's get started.

  • 01-07: The IdeaBlade references eliminate the need for these prefixes before IdeaBlade classes: CommandUtilities is the NameSpace for the CommandMap class used to implement commanding; and the four Windows references are for dealing with Guids and collections;
  • 10, 89-90: Used to implement property change notification, which sends changed values back to the View;
  • 12: Creates an IdeaBlade EntityManager object, which keeps track of changes and sends them back to the database; It also contains the generated query class used to return Prospects in the Find form that will be defined below;
  • 14: This is the collection where records - er, entities - returned by a query are stored; Prospect is the generated class that defines a record - er, an entity as well as the query for that table.
  • 16-17: prospect is the object that holds the current record from the Prospects table. Prospects form controls are bound to this object;
  • 19: This holds a new prospect that is created and then added to the prospects collection;
  • 21-22: This collection will store commands in a way that simplifies both command wireup and the Binding syntax;
  • 24: This is the constructor for the ViewModel class; it runs when the object is created in the View's Load event, as we'll see shortly;
  • 26: This instantiates the EntityManager class generated by DevForce for this database;
  • 28: This instantiates the prospects collection of Prospect records - er, entities;
  • 30: This instantiates the Commands collection object defined in the CommandMap class in CommandUtilities.cs;
  • 31-36: This adds six delegate commands to the Commands collection; in the next Listing we'll see how they're used;
  • 39-49: This shows a modal Find form to select a single prospect to be displayed in frmProspects. The key selected by the user, which is a Guid, is stored in App.ID;
  • 51-56: Not used unless you want the form to appear with one record already loaded;
  • 58-60: Uses a little trick to find the View form and call the form's Enabler routine to enable/disable its TextBoxes and Buttons;
  • 63-68: Adds an empty record to the prospects collection, adds a GUID, and assigns it to the prospect object for display on the View;
  • 70-71: Enables data entry controls and disables all buttons except Save and Cancel (see the View code-behind);
  • 73-78: Deletes the selected Prospect record and removes it from the prospects collection using the mgr object;
  • 80-81: Returns True if the Delete button should be enabled; or False if it shouldn't; this is a built-in behavior of ICommand (see CommandMap);
  • 83-84: Saves any changes and disables input controls and enables all buttons except Save and Cancel;
  • 86-87: Cancels any changes and disables input controls and enables all buttons except Save and Cancel;
  • 89-90: Required when you implemented the INotifyPropertyChanged interface up on line 10.

The strangest code in this ViewModel is this one:

46         q.Execute().ForEach(prospects.Add);

This means

"Execute the query; then, Add each row in the result to the prospects ObservableCollection,"

Binding the Click event on Buttons in a View to the corresponding ViewModel requires implementing the ICommand interface, which CommandMap does thanks to the DelegateCommand class in CommandUtilities.cs. Binding to data requires public properties, one for each column in each table, and these properties must have Property Change Notification built in. IdeaBlade entities do. Our prospect object, representing the prospect that's displayed on the screen, doesn't, and that's why we added it above on line 17.

The prospects collection is a public property (note the { get; set; } that implements the default backing store.) That's required. Remove the { get; set; } at the end, and it will compile just fine, but it won't work. You'll forget to add that a few times before you become completely familiar with ObservableCollections and binding.

Probably the oddest thing in this code is the occasional use of lambda expressions, i.e. "x => x." (e.g. line 45).There's a reason for this syntax, but I don't care. Just get used to typing "x => x." (or "z => z." or whatever) any time you want IntelliSense to show you your column names, and you'll be fine.

Now we can go back and add the binding expressions that tie the View to the ViewModel (Listing 6):

The addition of the attribute Text={Binding Path=FirstName}" causes WPF to search its current DataContext for a public property named FirstName. Since the current DataContext is an instance of the frmProspects_VM ViewModel class, and the Grid's DataContext is bound to prospect, it looks in frmProspects_VM.prospect, a public property of type Prospect (a single record - er, entity), where it will find a public property named LastName thanks to the Prospects class generated by IdeaBlade and declared in our ViewModel. Neat, eh?

Back in frmProspects, we need a little code to give life to our app (Listing 7):

The reason that the ViewModel object is available to the View is because we declare and instantiate it in the constructor of frmProspects. The declaration is scoped to the class. In the constructor, the ViewModel object is assigned to the Form's DataContext. That's the reason that the Binding code in Listing 5 works.

Enabler is a method to enable/disable TextBoxes and Buttons in the View. There are two reasons why I made Enabler() a public method in the form's CodeBehind: First, I won't need to test that logic in the unit tests; it's only meaningful in the UI, and you test the UI by running the UI. Second, since Enabler() is public, I can call it from the ViewModel (see the ManageControls method in the ViewModel, above.) The way that the ViewModel code is written, if the window isn't found, the code doesn't run, so it's harmless during unit testing when no views are active.

The last thing I need in my project is the FindAProspect form (I mean View) referred to on line 41 of Listing 4. My sample only searches for last names starting with the letter(s) entered by the user, but obviously you can make the search form as fancy as you want. The methodology is the same: Filter the collection based on user-supplied criteria, and then when the user selects a Prospect, save its key (which is a Guid, if you recall) to the public static ID field in App.xaml.cs. I just used LastName because it demonstrates one way to filter the data. The boldfaced code toward the end of Listing 8 shows how LINQ is to provide IntelliSense for SQL Queries. Pretty slick, ┬┐no?

Here's the form (Fig. 10):

I'll first list the xaml, then the codebehind:

If you've never used LINQ, the code in btnShow_Click will be somewhat puzzling. Prospects is actually an EntityQuery, which means it's the basis of a SELECT statement. LINQ exposes SQL with IntelliSense; so, each time you type a period, the PEMs (properties, events and methods) available at that juncture appear in a dropdown list. C# ignores whitespace, including spaces and carriage returns, so you can drop down to the next line before you enter the period for enhanced readability (or if you're a publisher and you have more vertical than horizontal space; welcome to my world). Finally, you execute the query, add all returned rows to the prospects collection, and assign it to the datagrid's ItemsSource.

The Where, OrderBy and ThenBy clauses, and any others that you might want to use, need a starting point for the object whose PEMs you're exposing, and "x=>x." means something like "an x such that the x's.." Just type it, and you'll be supplied with the available PEMs. It looks funny, but it works. After a while you'll use it without even thinking about it. Which is better than trying to rationalize such an odd syntax. But Microsoft gets to decide how we do our work, and they're always right, even when a mutant like this is the result. But it's the best of all possible syntaxes, isn't it?

<rant>No it isn't. Just off the top of my head, this would be better:

      var query = mgr.Prospects P

It's just a though, gods in Redmond...</rant>

btnSelect_Click shows what App.ID is for; it provides a place to store the selected Guid until we close the modal FindAProspect form and get back to the code that launched it, which then uses the value stored in App.ID to retrieve the selected Prospects record - er, entity and load it into the prospect object in frmProspects_VM, which exposes the columns as public properties (with Property Change Notification, thanks to DevForce), which allows the Binding Path=(columnName) attributes in the View to find and display the data. And since by default, Binding in WPF is TwoWay, changes on the form are pushed back to the public prospect object in the ViewModel for saving by the mgr object. Got it?

You can easily use a ViewModel for the search form as well, but it's not necessary. MVVM is used to enable unit testing; it's not a religion. Besides, you can add test routines in codebehind files; you just have to write separate [test] methods so that they don't require human input. For example, in the download, I've added a [Test] to the FindAProspect CodeBehind. It's described in the Unit Testing section below.

Speaking of unit testing, wasn't that the original objective? So let's do it.

Unit Testing

Unit testing is much of the reason for using MVVM instead of just putting all event handling in the code-behind. So it had better be pretty easy and pretty slick. It's both.

I use nUnit, because it's survived the test of time, and has tons of features. You can download it free from After installing, add nUnit.exe to your start menu (or nUnit-x86.exe if you're running a 64-bit processor). You'll be using it a lot. Then, add a reference to nUnit.Framework.dll, located in your C:\Program Files(x86)\nUnit folder, to your project references and Build the project.

Adding a test couldn't be simpler (well, it could, but that would require changing the way Microsoft has implemented usings, and that would add a lot of other complications. I miss FoxPro...<g>) Add using nUnit.Framework just below the namespace declaration in frmProspects_VM.cs file, and then add this:

[TestFixture, Description("Unit tests")]
class frmProspects_VM : INotifyPropertyChanged

If you add using NUnit.Framework before the namespace declaration, you'll have to use NUnit.Framework.Description("..."), because there's also a Description attribute associated with System.ComponentModel, and VS 2010 won't know which one you're referring to. I had never used usings except at the top of a code file, but it's never too late to learn something new.

Next, modify the GetFirstRecord method to look like this:

[Test, Description("Test for at least one record")]
public void GetFirstRecord()
{ if (prospects != null) prospects.Clear();
  var query = mgr.Prospects;
  Assert.Greater(prospects.Count, 0);

The [RequiresSTA] attribute is required. I had never seen this documented in IdeaBlade code, but trust me, it won't run without it.

I've also added a test in the CodeBehind for the search form, just to show that it works. I've got last names starting with "P" and "S", but not with "A". So I'll test whether a corresponding record is returned for each case, using the totally cool Values parameter:

[Test, Description("Returns at least one LastName starting with 'S' or 'P'; fails matching on 'A'")]
public void DataTest([Values ("A","S","P")] string ln)
{ if (prospects != null) prospects.Clear();
  var query = mgr.Prospects.Where(x => x.LastName.StartsWith(ln)).OrderBy(x => x.LastName).ThenBy(x => x.FirstName);
  if (ln == "A") { Assert.AreEqual(prospects.Count, 0); }
            else { Assert.Greater(prospects.Count, 0); }

Now, launch nUnit (or nUnit-x86) and use File/Open to point to your executable, in either the bin/Debug or bin/Release folder, and click on the GO button. If you have the test data from the SQL script in SQL Listing 1 loaded, you'll see the result shown in Fig. 10:

Unit testing can be as simple or as robust as you want it to be. Some developers write the unit tests before they build the forms. That's a little hard core for me, but whatever floats your boat.


WPF is a giant step forward in desktop application design, and MVVM is a good way to make full use of its powerful binding capabilities. Hopefully, this article has given you confidence to dive in and try it on one of your tables. Email me if you can't make something work. I've been answering all of my emails for 25 years at; no reason to stop now.

See 'ya :)


Copyright(C) Pinter Consulting, 2018Tel: +1 (650) 464-6924