Introduction

This article started out as a WPF DataGrid demo and a short article explaining how to accomplish basic tasks with the DataGrid. I have been digging into the WPF DataGrid over the past couple of days, and I am pleasantly surprised by what I have found. It is pretty easy to work with, and it produces pretty good results. I put together a demo to document the basic operations that I will need to perform with the DataGrid on an upcoming project, and I thought I would share it with the CodeProject community. In particular, I wanted to share my approach to drawing a drop-line on the grid while a row drag was in process.

As I wrote this article, it emerged that most of the way in which I deal with the DataGrid is driven by the Model-View-ViewModel pattern, and the article ended up being as much about MVVM as about the DataGrid. I think you will find it particularly helpful if you are trying to get a handle on MVVM, although even experienced hands will find the DataGrid discussion to be useful.

The demo app posted with this article gathers “How-To’s” in one place for the basic operations of:

Styling the DataGrid

Getting data to and from the DataGrid

Adding items to the DataGrid

Removing items from the DataGrid

Moving items by dragging and dropping them within the DataGrid

As you will see in going through the article, MVVM heavily influences almost every aspect of working with the DataGrid. For many developers, including myself, it is simply the way that WPF is done.

Running the Demo App

For the demo app, I needed a simple model with no natural order, so I borrowed the family grocery list from last Friday, and I made an object model out of that. It is the sort of list that one might use to perform all of the DataGrid tasks listed above. I haven't included data persistence in the demo, since there are so many ways of doing that. Instead, I create the object model at runtime.

When you start the demo, you will see a grocery list on a DataGrid. The grid has two columns:

Sequence: The sequence number of each item on the list. I include this column only so that I can verify that resequencing the list (which I discuss below) is being done when an item is moved.

Item: The grocery list item.

Here is how to perform the basic DataGrid operations described above:

Add item to list: Click in the blank row at the bottom of the list. The DataGrid will create a new, empty item and assign it the next sequence number. Type in a name for your item and hit enter.

Remove an item from the list: Select an item and click the Delete button above the DataGrid. The item will be removed, and the remaining items will be resequenced.

Move an item: Hold the Shift key and click on an item. Still holding the shift key, drag the item to another row, then release it. While you are dragging the item, a drop-line will appear on the grid to show you where the item will be inserted if you drop it. When you drop the item, the list will be resequenced.

And that’s about all there is to the demo. As I said initially, it is pretty simple.

Model-View-ViewModel Implementation

The demo is built around the Model-View-ViewModel (MVVM) pattern. I use a fairly conventional implementation of MVVM. There are several different flavors of MVVM in the wild these days, and a lot of the literature on MVVM doesn't make a distinction that I consider to be vital.

Two flavors of MVVM: MVVM evolved from two other patterns, Model-View-Controller (MVC) and Model-View-Presenter (MVP). Both patterns are approaches for moving business and control logic out of a UI (the View). In both, a coordinator class is placed between the UI and the domain model. The coordinator class communicates with the View, and it contains the business and control logic that otherwise would have gone into code-behind in the View.

However similar the two patterns may be, they are not the same. I personally draw the following distinction between the two patterns:

In MVC, the Controller is not supposed to know about its View. It simply exposes properties and methods that a View can use. It is indifferent to the View that actually consumes its services.

In MVP, the Presenter typically has intimate knowledge of its View; the View is really just an adjunct to the Presenter. In an MVP app, it is not unusual for the View to be a property of the Presenter, to facilitate easy communication between the two.

I have a strong personal preference for the MVC flavor of MVVM. I believe that the MVC approach gives me greater flexibility to change the View, without causing unintended consequences in the ViewModel. In other words, I believe it does a better job of promoting Separation of Concerns and isolating the View and the ViewModel from each other, while allowing easy communication between the two. I discuss the subject at greater length in my CodeProject article on MVC, which can be found here.

Accordingly, my ViewModel knows nothing about the View that uses it. The ViewModel is passed to the View by App.xaml.cs as a part of the application bootstrap process:

The view model is instantiated and set as the DataContext of the main window, which serves as the demo application’s View. From there, the XAML can access the properties of the view model using WPF data binding.

Elements of the View Model

In other respects, my implementation of MVVM is pretty simple. The view model is made up of the following classes:

MainWindowViewModel.cs: This is the main class of the view model.

DeleteItemCommand.cs: An ICommand class that deletes objects from the DataGrid.

SequencingService.cs: A service class that re-sequences the grocery list when an item is moved on the DataGrid.

IgnoreNewItemPlaceHolderConverter.cs: A value converter to work around a nasty bug in the WPF DataGrid. More on this below.

This composition of a view model using a main class, commands, services, and value converters is pretty typical of my MVVM implementations.

The MVVM pattern is designed to facilitate the use of WPF data binding. I don't know if the WPF implementation can be considered Version 3.0 of data binding, but Microsoft absolutely got it right in this version. WPF data binding dramatically simplifies the process of wiring a view to its view model. Just about everything is done as a simple binding:

The process of wiring up a view is simpler and quicker than it is in WinForms. That alone would justify a move to WPF.

View model properties: My own personal style of programming is to group items and to make heavy use of regions to do the grouping. In the demo app, the view model properties are grouped into two different categories, which is pretty typical of my MVVM implementations:

Command properties: These are ICommand objects which do the actual work of the view model. These properties are generally bound to the Command property of buttons and similar controls. The demo app has one command property, DeleteItem, which deletes an item from the <code>DataGrid.

Data properties: These are what we traditionally think of as properties. The demo app has two properties; GroceryItem and SelectedItem.

In some projects, I will include a third category of MVVM properties, UtilityProperties. These properties hold flags and other values that the view may need to provide to the view model. I didn't need them in the demo app, so it only has the two types of properties listed above.

Command Properties

In my MVVM implementations, the ViewModel does very little actual work. Instead, it acts as a coordinator object, and it delegates the work to command and service objects. Command objects are a standard element of the MVVM pattern, and again there are a couple of ways of implementing them. In my implementations, I like to put the main logic for each task in a command object. So, my command properties are all ICommand objects, and each is linked to a unique class that implements the ICommand interface.

The real benefit of the ICommand interface is that it provides a convenient framework for maintaining the enabled/disabled status of controls that are displayed in the view. For example, the demo app displays a button that deletes the selected item from the grid. The button is bound to the DeleteItem command property of the view model:

<ButtonCommand="{Binding DeleteItem}"...>

That property is linked to an ICommand class, DeleteItemCommand.cs. Every ICommand class must implement a CanExecute() method, which determines whether the command can be executed at any given point in time. Here is the DeleteItemCommand.cs implementation of the method:

.NET polls this method for all ICommand objects on a regular basis. If the method returns true, .NET enables any control bound to the command. If the method returns false, then .NET disables the bound control. In DeleteItemCommand.cs, the CanExecute() method simply checks the view model’s SelectedItem property to see if anything is selected in the grid. If so, the method returns true, and the button is enabled. Otherwise, the method returns false, and the button is disabled automatically by .NET. That’s another strong argument in favor of WPF.

Note that DeleteItemCommand.cs holds a reference to its parent view model, in the command’s m_ViewModel member variable. This reference was set when the view model initialized its command properties:

The view model instantiates the ICommand objects to which its command properties are linked, and it passes a reference to itself to the constructor of each ICommand class. This reference makes it easy for the command to check view model properties as it carries out its work.

The actual work of an ICommand is performed in its Execute() method. In the demo app, the work is very simple. The Execute() method gets the currently-selected item from the view model and deletes the item:

Data Properties

Data properties are pretty straightforward, because they resemble the object properties that we have used in .NET from the beginning. The only twist is the WPF requirement that data properties in the view model raise the PropertyChanged event, so that the view can be updated when a view model property changes.

In the demo app, we fulfill this requirement in two ways. First, we derive the view model from an abstract class, ViewModelBase.cs, that is located in the UtilityClasses folder of the demo app. The class implements the INotifyPropertyChanged interface, a .NET interface that requires implementing classes to provide the PropertyChanged event. The ViewModelBase class also provides a method, RaisePropertyChangedEvent(), to raise the event when a property changes.

The form of the data property declaration allows us to invoke the RaisePropertyChangedEvent() in the view model base class when a data property changes. That’s what keeps the view and the view model in sync with each other.

Service Classes

There are some tasks that are either:

Used by several commands

Lengthy enough that I don't want to clutter up command objects with their code, or

Invoked by the view model, rather than a control in the view

I use service classes, which I treat as part of the view model, for this code. In my MVVM implementations, service classes are generally static.

NHibernate quirkiness: In the demo app, we have one service class, SequencingService.cs. My applications generally use NHibernate for data persistence. I am a big fan of NHibernate; it drastically reduces the time spent on creating code to load objects from a database and save them back. But it does have a few quirks.

One of the things I like best about NHibernate is the fact that it does automatic ‘dirty checking’. It will save only objects that have changed, which speeds up data persistence considerably. But for this feature to work, we have to be fairly careful to preserve the identity of the objects we read in from the database. For example, if we reorder a collection we have loaded from a database, NHibernate will consider the reordered collection to be a new collection, and we will lose automatic dirty checking. Fortunately, we can add objects to the collection, and delete objects from it, without losing dirty checking.

But it turns out that NHibernate also has an aversion to the ObservableCollection<T> collection type that MVVM is built upon. To get around this limitation, I created an application that wraps plain vanilla IList<T> objects, which NHibernate likes, in ObservableCollection<T> wrappers, which WPF likes. You can find the application and documentation here.

The demo app included with this article doesn't involve NHibernate, but my upcoming production app, for which the demo app serves as a pilot project, does. In that app, I am going to need to save a sequence number for each object in the collections displayed by the view, so that the objects can be loaded in the correct order the next time they are read in. That turns out to be a fairly simple task.

When we use wrapper objects as described above, then when we drag and drop items in a data grid, it’s the wrapper objects that get reordered, not the domain objects. The domain objects remain in their original order in the domain collection. All we need to do is resequence the wrapper collection after a move, an add, or a delete.

The SequencingService class and the ISequencedObject interface: The SequencingService class takes care of that. It has one method, SetCollectionSequence(), which simply runs through the list and renumbers each item according to its current index:

The signature of this method warrants some explanation. In my production application, I will have several collections that will be displayed by the app’s views. These collections will not necessarily derive from the same base class, so I have created an interface, ISequencedObject, so that I can pass any of these collections to this service method. The interface file is located in the UtilityClasses folder of the demo app. It contains a single property:

publicinterface ISequencedObject
{
int SequenceNumber { get; set; }
}

As a result, the SetCollectionSequence() method can process any ObservableCollection<T>, so long as the elements of the collection implement the ISequencedObject interface. That is what the where clause at the end of the method signature signifies.

Service classes are frequently invoked from ICommand objects. However, the demo app shows a different reason for using a service class. Resequencing a collection is not triggered by a button or other control. Instead, it is invoked when the grocery list changes. That is, when an item is added to the list, removed from it, or moved within the list. In its Initialize() method, the view model subscribes to the CollectionChanged event of the grocery list:

p_GroceryList.CollectionChanged += OnGroceryListChanged;

When the event fires, an event handler in the view model invokes the sequencing service:

We could have simply placed the resequencing code in the event handler, but in a complex production app, a view model can get cluttered pretty quickly. And in my upcoming app, the code will be called by a number of different view models. Those requirements call for a service class that is accessible by whoever needs it.

Keep in mind that the sequencing service is not required for either the WPF or MVVM. Its need stems from my fairly unique requirements, which stem from using NHibernate with the WPF DataGrid. Nonetheless, even assuming these requirements do not apply to your application, the service class demonstrates one approach to where and how to use services in an MVVM application. It is an approach that has worked very well for me, and I have no hesitation in recommending it for general use.

Value Converters

Value converters are another frequently-used element of the MVVM pattern. WPF generally communicates in terms of strings, and we use value converters to convert object values to their string representations. The classic example of a value converter is a date converter, which might convert a DateTime object, which has a default string representation of “9/20/2009 12:00:00 AM”, to a more user-friendly representation, such as “Sunday, September 20”.

We don't have any naturally-occurring value conversion needs in the demo app, but we do have a very important use for a value converter nonetheless. The version of the WPF DataGrid included in the Pre-C# 4.0 WPF Toolkit has a fairly subtle, but very nasty bug. If you data bind the DataGrid’s SelectedItem property to a view model (as the demo app does), you can no longer use the DataGrid’s ability to add a new item to the grid by clicking on the blank row at the bottom of the grid. If you try to add a new item that way, you will get a FormatException with practically no explanation of what happened or where it happened.

Thanks to Nigel Spencer, who documented this bug and provided a clever fix. It seems the problem lies with the value that the DataGrid generates for a new item. The problem can be avoided by using a value converter that simply ignores that return value. That’s what the value converter in the demo app does; it is a direct copy of the one suggested by Nigel. You can read more about the bug, and Nigel’s solution, here.

Note that we have to declare the value converter in code—see the class file IgnoreNewItemPlaceHolderConverter.cs. But we also need to reference the value converter in the XAML of each window with a DataGrid. In the demo app, we do that in the <Window.Resources> section of the main Window XAML:

As you will see below, it is more usual to place resources such as this in a ResourceDictionary, where they are accessible to multiple windows. With that, let’s turn to the DataGrid itself.

Basic DataGrid Operations

As I discussed at the outset, there are three DataGrid operations that most applications need to support: adding items to the grid, removing items from it, and moving items up and down in the grid. Before we get to those operations, let’s take a look at styling the grid.

Styling the DataGrid: The DataGrid is styled in XAML. In the demo app, we place the style in the <Window.Resources> section of the main Window XAML. But in production apps, it is more usual to place the style in a ResourceDictionary, where it can be shared among several windows. And in a complex application, where grids may be located in many different assemblies, the styles may be placed in a special resource dictionary located in a ‘shared resources’ assembly. You can read more about that here.

The styling itself is pretty straightforward. The main window contains three styles:

The first defines a gradient brush that is used as the grid background. The second style defines the appearance of the DataGrid, and it references the first. The third style is used for dragging and dropping items within the DataGrid, and we will discuss it further below.

By and large, the styles are plain-vanilla XAML, and they do not warrant a lengthy discussion here. If you need more explanation, MSDN and most WPF books have pretty good discussions of the subject.

Adding items to the DataGrid: This task is about as simple as it gets. When you click on the blank row at the bottom of a DataGrid, the control creates a new, empty item for you and adds it to its collection. Thanks to the magic of WPF data-binding, the change is automatically propagated to the view model collection to which the DataGrid is bound. In the demo app, that collection is the GroceryList property. As you add an item to the grid, note the sequence numbers in the first column and the item count at the bottom of the window. Both of these values are being taken from the view model property, not from the grid itself.

The DataGrid is bound to the GroceryList property through the grid’s ItemsSource property:

In short, all we have to do is set up the data bindings; the DataGrid does the rest of the work for us.

Removing items from the grid: This task requires just a little more work. We have already discussed it above, in connection with the MVVM implementation. The Delete Item button, located in the main window just above the DataGrid, is bound to the DeleteItem command property in the view model. That property is linked to the DeleteItemCommand.cs class, whose Execute() method performs the actual work.

Moving items within the DataGrid: This is about the only task that requires any explanation. The implementation in the demo app, is taken from a code sample published on MSDN by Ben Carter, a member of the WPF development team. The demo app adds drop-lines to Ben’s implementation, but otherwise, it is taken straight from his code. When you drag an item to another row within the grid, you will notice a blue line that follows your cursor up and down the grid, indicating where a dropped row will be inserted. I had previously added that feature to a WinForms data grid, and that implementation required some fairly complicated owner-draw code. In WPF, it takes just a couple of lines of simple formatting code. It’s just one more reason to love WPF.

No code-behind: Before we get into the specifics of how the drag-and-drop functionality works, take a look at the code in MainWindow.xaml.cs. It appears that I have broken one of the cardinal rules of MVVM:

A view should delegate its work to its view model, rather than relying on code-behind. A well-designed MVVM application has almost no code-behind in its views.

Obviously, in the demo app, the main window of the demo app has quite a bit of code-behind. You might well wonder what that is all about.

I am a big believer in the “no-code-behind” principle, and I don't think I have violated that principle in the demo app. The idea behind no-code-behind is to move control and business logic out of the view to a controller or coordinator layer that mediates between a view and the domain model.

Now take another look at the code-behind in the main window. You will notice that all of the code is related to the drag-and-drop functionality of the data grid. That functionality is a display concern, and it is therefore the province of the view. None of the code deals with business logic or control issues. Accordingly, Separation of Concerns is preserved.

In a larger application, with multiple views and numerous data grids, you might want to remove the guts of the code to a service class for all views, which would be invoked by skeletal event handlers in each view. That approach would eliminate duplication and provide a single point of change for updating the code. But in a simple application like the demo app, there is absolutely nothing wrong with placing view-support code of this sort into code-behind.

So as you develop applications using MVVM, take the no-code-behind rule with a grain of salt. If you need to program display logic that cannot be expressed in XAML, then code-behind is a perfectly acceptable place to do it.

Implementing drag-and-drop: The drag-and-drop implementation is really very straightforward. It has three elements. First, we add the events that we need for drag-and-drop to the DataGrid’s XAML:

Again, this code follows the general .NET pattern for drag-and-drop, so we won't discuss it at length.

Implementing a drop-line on the grid: What is worth noting is the implementation of a moving drop-line, which indicates where a dropped row will be inserted. The demo app implements a drop-line by setting either the top or the bottom border of a data row when the cursor enters that row, and then clearing the border when the cursor enters a new row.

When a drop is made, the WPF DataGrid will insert a dropped item either above or below the row under the mouse pointer at the time of the drop, depending on the direction of the drag:

If the item is being dragged...

When dropped, the item will be inserted...

...above its original row

...above the row under the mouse pointer

...below its original row

...below the row under the mouse pointer

So, the first order of business is to determine the direction of the drag. We get the original row index from the OnMainGridMouseMove() event handler:

We store the index in a member variable in the window class. Next, we get the current row index as we drag the row upwards or downwards. We get that from the OnMainGridCheckDropTarget() event handler (see below). Then we compare the two values. If the result is negative, the drag is upward, and we draw a border on the top of the row under the mouse pointer. If the result is positive, the drag is downward, and we draw a border on the bottom of that row.

This feature was added to the demo app to simplify the process of distinguishing between two types of drags:

A drag meant to select multiple rows, and

A drag meant to move a row to a new location.

If the Shift key is pressed, the selected row will be dragged. If the Shift key is not pressed, multiple rows will be selected.

As you can see, basic grid operations are surprisingly easy to implement in the WPF DataGrid. Not even the code for the drop-line is very complicated

Conclusion

As we noted at the beginning of this article, MVVM is a very scalable pattern, lending itself well to simple applications, such as the demo app, and to much more complex, multi-assembly applications. However, that does not mean that MVVM can support complex enterprise applications on its own. As an application grows larger, the essential problem becomes how to partition the application into manageable pieces, and how to integrate those pieces into a single, functioning whole.

I am very enthusiastic about the solution that Microsoft has provided in Composite Application Guidance for WPF, otherwise known as Prism. Prism is an application framework that allows a developer to partition an application into modules, which load into a shell that serves as the main window of an application. Prism uses some very clever mechanisms to allow the modules to communicate with each other and with the shell without becoming tangled up with each other.

As of this writing, Prism is now in Version 2.0. Unlike the earlier Composite Application Block library, Prism is not an all-or-nothing proposition. You can use as much or as little of it as you like. But Prism integrates so well with MVVM, and it is so well designed, that I find myself using just about everything it has to offer. It is definitely the next step to take after you gain a comfort level with MVVM.

And with that, I'll put down my pen. I invite any comments or suggestions you may have for this article; I find that I learn as much from reader comments as I do from writing the article itself. If you haven't spent a lot of time with MVVM, I recommend it to you. And if you haven't yet used the WPF DataGrid, it is a well-designed, easy to use control that integrates well with MVVM. I hope it simplifies your development chores as it has done for me.

Share

About the Author

David Veeneman is a financial planner and software developer. He is the author of "The Fortune in Your Future" (McGraw-Hill 1998). His company, Foresight Systems, develops planning and financial software.

I work on a MVVM application and I cant populate my datagrid after a selection in a combobox.I've try to populate a textbox and it's work fine but it's not the case with my datagrid and I dont find my mistake.

I have implemented a portion of your article in order to help with the problem of clicking on the last row to create an additional item. I have a custom `DataGrid` that inherits from `DataGrid`, but the application of the converter does not seem to work in my case due to the override of the OnPropertyChanged event.

My problem is, I have a datagrid having files and a download button each row. Clicking download button I want to show download progress at corresponding row. Is it possible ? Can you shed some light on this?

Code behind is in IMHO absolutely accurate if it is concerned only to the view apects. I do not see any violation of the seperation of concern. Rather, it guarantees that view specific stuff does not clutter up the ViewModel, which would make the ViewModel less reusable and tightly coupled to some sort of controls.

This would have to be one of the clearest, most concise & well thought out article that I've read in quite a while. Thank you so much for taking the time to write it. Even faced with dogmatic & unbelievablly rigid comments from one reader, you stuck to your guns (appropriately so in my book) & remained focussed & polite.

I agree with every one of your philosophies & reasonings presented here. Blindly sticking to the "rules", as was suggested by that particular reader (& anyone else who advocates it), for the sake of being "pure" is just rediculous. As you correctly pointed out, whether you used the exact words or not, MVVM is a "pattern", not a set of rigid rules to be followed at all costs.

Of course your view's code-behind is not "unit testable", it's "view-specific" & has nothing to do with business logic, or even domain logic, so why on earth would someone want to test it in the first place.

I guess some people just like to argue for the sake of it, even if it exposes their own ignorance & lack of flexibility.

Great work! I gave it a well-deserved 5. I hope to read more of your articles in the future.

I am new to WPF and MVVM, but I was hoping to avoid polluting my Domain Objects with INotifyPropertyChanged implementation. I know that INotifyPropertyChanged isn't exclusively UI purposed, but in my experience I would rarely need it if it weren't for 2-way data binding.

In your example, you do receive notification of adds, removes, and moves within the list, but you will not receive notification of an update to one of the properties of GroceryItem.

Is the answer simply that I SHOULD implement it in the Domain Model (even if I only need it for the UI)?

And on another note, though the article helps me understand MVVM, isn't this a tremendous amount of code--considering the simplicity of the app?

I think you missed the point of the article, which demonstrates a non-dogmatic approach to MVVM, with particular care given to Separation of Concerns.

Yes, in a simplistic approach, all code would go in the View Model, and that's where most novices start. But look at the code carefully. All of the code in the View relates to the UI--displaying dialogs, handling needed events and so on. Events that relate to back-end concerns immediately delegate their work over to the ViewModel.

In other words, the View contains all code that concerns the UI, and the View Model acts as a facade to the back-end of the app, and it handles all back-end concerns. That's generally considered best practice in implementing Separation of Concerns in a line-of-business app.

I discuss these issues specifically in the article. Re-read it, and I think you will understand the code better.

No, actually this article has missed the point of MVVM and the separation of concerns.This article is misleading; there should be NO code in the View, period. Not even a “hook” as you’ve mentioned in replying to another post on DataGrid selection click events.The WPF concepts of DPs, binding and Commanding proves this.

Check out postings from others e.g. Josh Smith and the rest of the WPF Disciple crew for a start. Perhaps look into some of the MVVM frameworks that have sprung up over the last 12 months. That's MVVM frameworks NOT Prism btw.

MVVM came to the fore as a result of its predecessors i.e. MVP, MVC to name but two from a whole raft of presenter patterns. Both of these advocate NO code in the View.

Sorry to sound like a boring theoretical purist; but if you go down the MVVM path then you should implement it 100%

Well, you are certainly entitled to your opinion, but it goes without saying that I think you are dead wrong. Statements like "there should be NO code in the View, period" are dogmatic and pedantic. Consider:

I am writing an app that will initially target the desktop, using WPF and MVVM. However, the app may very well migrate to the Web soon after it goes gold. If that happens, the UI will need to be rewritten. I isolate those changes to the View by segregating all UI-related code in the View. As a result, even in a Web-based app, my View Model will be about 80% reusable. If I loaded up the View Model with pure UI code, it would have to be completely rewritten.

"Sorry to sound like a boring theoretical purist; but if you go down the MVVM path then you should implement it 100%" Apology accepted. You should never implement anything 100%. Use your judgement, and tailor the suit to fit the person who wears it, not the other way around.

Your approach is OK for a “one man band” software development effort. Hack it !

However, in a large development team environment, agile, continuous build scenario, your approach is doomed. It’s not repeat NOT, MVVM. It is simply not recognisable as any form of Presenter Pattern.

Ok, so how do you Unit Test with the code in your article, answer, you don’t, you can’t.Think of a project with say, 20+ developers working on it, all checking in code, continuous integration etc. Then let’s say, Cruise Control doing the builds and recursively running Unit Tests.A separate Test team picking up the builds to formulate release candidate builds etc.

How do you test the code and logic in your View? You Can’t. You’re on the road to large scale system failure and more worryingly; high maintenance costs in supporting addition functionality in the coming months.

Hence the need for Presenter Patterns and the separation of concerns, move code from the View for starters.You should be able to inter-change the View i.e. ASP.NET, WPF, WinForms, ComandLine, Unit Test Mocking ; the frontend should interact with the ViewModel and have no concrete implantation dependencies with it. (Dependency Injection, but that’s another story).

<quote>“ I am writing an app that will initially target the desktop, using WPF and MVVM. However, the app may very well migrate to the Web soon after it goes gold. If that happens, the UI will need to be rewritten. I isolate those changes to the View by segregating all UI-related code in the View. As a result, even in a Web-based app, my View Model will be about 80% reusable. If I loaded up the View Model with pure UI code, it would have to be completely rewritten.”<end quote>

And in particular this line:

“If I loaded up the View Model with pure UI code, it would have to be completely rewritten.”

You have totally missed the point of using any form of Presenter Pattern.

To anyone else reading these comments, do NOT implement MVVM as this author suggests it’s not correct.

You may like to reference this article for starters, a nice clean and very basic implementation, to get the ball rolling.

http://www.codeproject.com/KB/WPF/FromRussiaWithLove.aspx.

Then check this chap’s work as well, he posts his work on this web site as well.

No, I am absolutely correct, and you are welcome to come down as hard as you like. However, I would suggest that, instead of criticizing the work of others, you would better spend your time and effort writing an article of your own, since you obviously have rather strong feelings on the subject.

When I first began using MVVM, I started where you seem to be. I followed the "rules" blindly and religiously. And I can certainly understand that in a large, bureaucratic shop, where most programmers don't really know very much about the technologies they use, the restriction of individual judgement and decisionmaking is probably a desirable thing. If that's the sort of environment you enjoy, more power to you.

As I worked more with MVVM, I discovered problems with slavish adherence to the "rules". In short, my view models became sucked into my views. That's when I saw a benefit to stripping all UI code out of my view models and putting it back in the view, where it belongs. If you disagree, that's fine. But to tell me I'm wrong, that's laughable.

I hope that at this point you will take my suggestion and write your own article. It's a much more positive approach than inciting a flame war.

Your article is titled “MVVM and DataGrid” it should have been titled “DataGrid”.Your code is not MVVM, it’s as simple as that.

Why not get an independent adjudicator to look at your code, email Josh Smith for example.

I develop code for an Investment bank in London (having come from a 18 year real-time engineering software background).In this large development team we write our Model, ViewModel and Unit Test, very much TDD.We don’t think about the View, well of course we do, we just don’t code much of it. We have a couple of graphics designers who do all the sexy XAML stuff. We agree an interface mechanism with the designers and that’s about it.Therefore we as developers can write the system from unit tests, (and very basic wireframe Views) at a later stage we simple plug the actual View into the system, and bingo, successful large scale integration.

Because we implement MVVM with no code in the View we can do this, and it works wonderful.Your method is doomed to failure; you are misleading novice readers about MVVM.

I do not contribute articles; basically I’m just too busy, work and play. There are some truly gifted developers out there who do post first rate articles on numerous subjects. Why should I replicate their wonderful work?

Unfortunately, this article is poor, misleading and not correct.

Check Josh Smith’s work (link below) , you’ll see no code in the View, and a correct interaction between the View and ViewModel via the use of Routed Commands.

The way you work with MVVM is wrong. Call it what ever you want but don't call it MVVM.

Anyway, this is my last reply, you clearly believe your way is correct, fine you go on ahead and work that way, but please do not coerce others into your way.Simply point them to the posting I’ve link to in this reply.

I wish you success in your future endeavours. Regards from a wet and windy London

My, my, my... Who's the one trying to do the coercing here? The article, and hopefully my discussion, have been built around the principle that there are different paths up a mountain, and that the thoughtful developer will evolve a pragmatic approach where the solution is tailored to the problem at hand. Sometimes the solution leads to bending, and occasionally outright breaking, rules that one learned when first working with a design pattern.

Your argument, on the other hand, is that there is one one way to implement MVVM, and that way must be followed. The rules must be obeyed. That sounds pretty coercive to me.

An 'independent code adjudicator'? Wow--more coercion into right-thinking. I would surely hate to work in your shop if that's what you folks have to resort to. It sounds like the Ricky Gervais version of The Office.

As to Josh's implementation of MVVM, yes, his and mine differ in some respects. Josh has said that he prefers for his View Models to have intimate knowledge of his Views. That's how he gets all the code, including UI code, out of his Views. I don't use that approach, because I think it leads to the View Model being absorbed into the View. I like to keep my View Models a little more separated from my Views. Consider me a Dissenter.

There are two different prototypes for the MVVM pattern. One is the Model View Presenter pattern, where the Presenter is an adjunct to the View. The other is the Model View Controller pattern, where the Controller acts as a facade to the app back end. Josh has said that he considers his View Models as being akin to Presenters, where mine are more in the nature of Controllers.

In MVC, you keep UI code out of the Controller, just as you keep business and infrastructure logic out of the View. The ideal behind MVC is that you can completely replace the View without touching the Controller or the back end of the app.

In MVP, a Presenter is created to drive a specific View. It acts as an adapter between the View and the Model (Josh's words). If the View is changed, the Presenter must generally be changed, as well.

One big difference between the MVP and MVC flavors of the pattern has to do with whether the View Model knows about the View that uses it. IN the MVP variant, the project that contains the View Model needs a reference to the project that contains the View. In the MVC variant, the View Model has no knowledge of the View, and the ViewModel project does not contain a reference to the View project.

I have a pretty strong preference for the MVC variant of the pattern. As I said in a previous post, I think it does a better job of isolating the UI code. But notice that I didn't say Josh is wrong. He and I simply use different variations of the same approach, based on different sets of preferences. Both MVP and MVC are legitimate prototypes for the MVVM pattern--they will simply lead to view models that differ somewhat in approach.

And no, I don't believe that may way is 'correct'. This 'correct' and 'incorrect' nonsense is something that you brought into the discussion. I have said that I have found my approach to be useful, and I am pretty pleased with how well it works. If it offends you that I have, in your words, broken the rules, then you may deny my approach the title of Model View ViewModel. But you cannot deny it the title of "MVVM". It would still stand for 'Mr. Veeneman's View Model'.

Jason Dolinger's presentation is actually quite good--it is a valuable learning resource for WPF. If you take a close look at the presentation, you will notice that Jason uses MVVM to move business logic out of code-behind, which I would agree is a good thing.

Jason does not really deal with the issue of presentation logic. His concern is with separating presentation logic from business logic, using MVVM. Jason's demo has only one window, so it does not deal with the issue of how to handle common dialogs and events for which there are no data bindings.

Those are the two cases where I add code to the View. Common dialogs are invoked from the ViewModel, but they are displayed by the View (since they are presentation artifacts). My code uses events to perform the callback from the ViewModel to the View, in order to keep the dependency running from the View to the ViewModel.

Events that have no data bindings are handled by code-behind handlers that immediately delegate out to View Model methods. I generally delegate to 'command properties', to keep things consistent with the majority of cases, where I data-bind to a command property.

This all comes down to a family of patterns known as Separated Presentation. These patterns provide guidance on separating business and presentation logic. Microsoft has a good write-up of the approach in the documentation to Prism 2.0[^] at pages 72-73. If you are considering writing a WPF app of any complexity, I recommend Prism as an application framework, and I would recommend the discussion of Separated Interface whether you are considering using Prism or not.

Thanks for this article David. I agree with you that patterns are for guidance, and need not be followed dogmatically. It is usually easy be dogmatic when solving a specific problem in a demo, but when the situation gets more complicated, trying to do everything the "MVVM" way could easily double your dev time. (Enough said...)

Well, about the demo. I had an expectation that the "DeleteItemCommand" would also handle the case where the user selects an item and hits the delete key on the keyboard. From debugging the demo, this action still deletes the item, but does not use the DeleteItemCommand. How can you link these 2 actions to the same command?

Example Scenario:You want to do some validation before deleting an item from the grid.

Expected Behaviour:You want the validation code in DeleteItemCommand to be run regardless of what 'delete' action the user does (i.e. Hit delete button on UI, or use delete key on keyboard)

Current Behavoiur:It appears validation will only be done when user hits delete button on UI.

We have a couple of graphics designers who do all the sexy XAML stuff.

How do u unit test all the sexy xaml stuff like triggers, transitions and so on? Well my guess is u don't, because u can't, because it's UI. Displaying data is concern of the view. Doesn't matter if you implement all the display logic in a declarative way or as code behind... but that's just my point of view on this topic.

That's all fine, you code how you want, but it really isn't MVVM any more. These patterns are given names to facilitate communication between developer's and what you're presenting here is more like a VB6 approach to GUI development. Put logic in the view, screw any testability.

If the View Model has methods to abstract ideas like "selection in a list", enabled state etc. then the view (presentation layer) may have logic to render these to a particular platform (HTML, WPF etc), but to me you're moved far from that approach. Sorry, but you don't get to define what MVVM is, Microsoft already did that.

"If you don't fail at least 90 percent of the time, you're not aiming high enough."Alan Kay.

>There seems to be a lot of code in your View, surely this should be moved out to the ViewModel.>How would you Unit Test with all that code in the View?

There is a lot of code that is not eligible for unit-testing (assuming the standard-paradigma of unit-testing the business logic). Do you use any converters, validation, resource lookup in your XAML? Resource hierachies, maybe satelite assemblies? Does your XAML use bindings to other Elements in the visual tree? Do you know what a template selector is? How do you unit test that?

Further: How do U unit test the effects of focus moving between controls, mouse moving, maybe drag and drop?

Statements like "There should be no code in the view" sounds a little bit like "No function should have more than 50 lines...." (your mileage may vary - consult your coding standards). If someone insists on such a rule under all circumstances, he proves to me that he understands nothing.

I am using the WPF Datagrid with an underlying MVVM collection. The user is able to update directly in the grid. The individual cells validate and I get the red border, etc. when appropriate. However, when the user clicks off the current row I need to cancel the move if the current row has broken rules. The collection class correctly sets a CurrentItem property when selection changes and it appropriately sets the grid SelectedItem back to the CurrentItem in the SelectionChanged event. The grid, however, is still highlighting the "new" row and the dataGrid CurrentItem property is out of sync at that point. I have tried setting the grid CurrentItem property, I have IsSynchronizedWithCurrentItem set to True, I have bound the SelectedItem property to the CurrentItem property but can't seem to get any combination to get the grid to leave the SelectedItem and CurrentItem on the row withe validation errors. Any ideas on a way to simply set an e.Cancel flag or reset the CurrentItem on the grid when validation fails?

No. I can cancel the selection change and focus actually remains in the correct row but the datagrid highlight does not reflect the cancel. I have it now where BOTH the old and new are highlighted which is a little more intuitive but still not good.

I had hoped that VS2010 would solve the issue so that is disappointing.

Thanks for your reply. That's my problem exactly.Any possibility of sharing how you get both highlighted instead of just the new one? Disappointing really isn't the word. I'm using it really simply and have hit several basic bugs.

My code is wrapped up in a couple of separate projects but I think these are the pertinent parts. I am using an ObservableCollection as the base and I don't know how it would change if you are using a different collection type for your grid.

I start with an EntityFramework object (Booking) and create an ObservableCollection for that object. That collection has a "current" property which implements the INotifyCurrentChanging interface.

It isn't pretty and I am still playing with the UpdateLayout() line because it is not doing what I expect. I have a feeling it is either not necessary or is in the wrong place. The cancelled variable is necessary since the SelectionChanged event occurs twice for every change and since you actually change the SelectedItem in the SelectionChanged event it fires four times. I found some articles on why that is but that is another annoying problem since you have to make sure you allow for it.

For me, this leaves the form with two rows highlighted and focus on the row I started from. It does really odd things if you allow multi-selection and the user hits the up/down arrow instead of clicking on the new row but that happens less frequently for me than clicking so this is as close as I have gotten to a "solution". It still feels like a hack at best but at least doesn't leave the highlighted row completely out of sight.

If there seem to be parts missing let me know. I use the collection class for other functionality and have some other checks in the events as well so may have missed something when I was cutting the code up.

If anybody else has any ideas on better options please weigh in. This missing functionality of the grid is a real pain in real world applications.

Hello and thanks for this great article. I'm new to WPF and I learned a lot about not just the DataGrid but about WPF Commands and bindings by applying this example.

I have a question about specifying a Command for a ContextMenu MenuItem. Your example has a Button specifying a DeleteItem command. Of course this works, but I also wanted to apply the command to a MenuItem of a ContextMenu that is applied to the DataGrid. I naively did the same Command binding as your button:

<MenuItem Header="Remove Item" Command="{Binding DeleteItem}"></MenuItem>However, at run time I'm getting errors that this binding cannot be found for the context menu. Now I know that there are a ton of things that can be set such as the RelativeSource and the CommandTarget and the FocusManager.IsScope property, etc. Can you please suggest the correct approach for this case?

Use an event handler in the code-behind. But--don't process the event there. Immediately delegate to a method in the view model. The view should only trap the event, and the view model should process it.

Don't know that you really need it--it's pretty simple. First, I already bind the SelectedItem property of the DataGrid (in XAML) to a view model property called SelectedItem. You can see that in the article. So then, I would simply trap the MouseDoubleClick event (again in XAML) to a code-behind handler named OnMouseDoubleClick():

Different developers do it different ways. In a production app, I avoid having the view know anything about the domain. My production views generally know only about their view models. Some people think I'm a bit extreme, but it works well for me.

I am not dogmatic about this rule--there are times when I make an exception, but that is an unusual case. And I did relax the rule in the demo app a bit, to make it easier for learners to follow.

So, if I wanted to "purify" the example and remove the reference in the View to the GroceryItem and make it go through the ViewModel, what would that look like? Can you describe it for me in a couple of sentences?

There are actually two different types of models in an application. The domain model is a model of the business problem addressed by the application. The view model is a model of what is displayed in a view. So, a domain model can have several view models, and each view model is a subset of the domain model.

View model properties are often simply objects that wrap domain objects. They typically expose only those properties of a domain object that are needed for the current view. So, If I have a complex OrderItem domain object, and I only need the SKU, item name, and price for a Catalog view. The OrderItemWrapper object for the CatalogViewModel would expose only those three properties of the OrderItem project.

You can read a lot more about wrapping domain models in my article, The WPF-NHibernate Toolkit[^]. There is a demo in that article that uses a view model to isolate the view from the domain model.