Published: 21 Jun 2009
By: Dino Esposito

Dino will briefly go through some patterns that help organizing the presentation layer and then focus on a new control in Silverlight 3 that makes data entry a pleasant breeze.

Contents [hide]

Introduction

A significant share of Web and Windows applications exists only to let users edit and save data. Data? What data? Unfortunately, each application has its own “data” to edit and save. The shape of data depends on the problem domain and any relational model associated with the application.

For years, most of the architects’ efforts have been aimed at exploring effective ways to automate and simplify this process. Data binding is the premiere technique that has been developed and incorporated in frameworks to save programmers most of the vanilla code necessary to read source data and copy into target properties. Data binding is simply a bridge between a source and a target and doesn’t say anything about the format of the data. The data source of a binding context can actually be any object.

Data-driven applications often need to edit and save data that is in the form of a table record or that can be easily abstracted from a table record. The Active Record pattern is an excellent strategy to smooth the process of persisting data to a database table. According to the pattern, you abstract a class from a table row and make this class responsible for its own persistence. In this way, a table Customers will originate a Customer class that knows how to load from the database and how to save changes back.

Will this Customer class be a good candidate to bind to the presentation? As usual in architectural debates, the correct answer is “It depends”. In this article, I’ll briefly go through some patterns that help organizing the presentation layer and then focus on a new control in Silverlight 3 that makes data entry a pleasant breeze.

Presentation and Patterns

Editing data typically requires some interaction with the user. In turn, interaction with the user requires a presentation layer with controls and widgets plus some surrounding code to format and validate data. In the end, you actually need much more than a set of text boxes and drop-down lists. To start out, you need a binding layer to populate user interface controls. Next, you need a UI validation layer that can properly and timely inform the user about wrong data and exceptions.

For a system that is mostly about data entry, the aforementioned Customer class (and the underlying Active Record pattern) may be a valid answer. Active Record, though, is a pure persistence pattern not specifically designed for the presentation. However, in a scenario where you mostly need to capture and store user entries, with no major extra work, the Customer class can be happily employed directly in the presentation and bound to UI controls.

Instead, for a system with a significant amount of logic (domain logic, formatting, UI validation) you might want to resort to a specific view model object. In doing so, you don’t spoil domain objects with formatting and UI validation instructions; at the same time, you place in this “view” object any extra presentation logic and keep data binding code as clean as possible. The target pattern is Presentation Model or, as renamed in the .NET space, the Model-View-ViewModel (MVVM) pattern.

MVVM is particularly effective in user interfaces built using Windows Presentation Foundation (WPF) and Silverlight because these platforms provide a superb support for (two-way) data binding. Using MVVM means that you place your binding stuff in the XAML markup and keep the code-behind class empty. The target of the binding is an ad hoc “view” object fed by the data model and instructed to assist the end user during the editing phase. The view object exposes properties that model the UI desired for a given chunk of data mapped to one or more records in some database tables. It also contains annotations for the exceptions to throw and messages to display in case of wrong and unacceptable values.

In more general terms, MVVM is a variation of the classic MVP pattern and it is still based on three actors: Model, View and Presenter. In MVVM, the presenter incorporates a ViewModel object whose properties exist to be bound to the view elements. The view is extremely passive and doesn’t expose any interface towards the presenter as in MVP. Figure 1 illustrates the model behind the MVVM pattern.

Figure 1: An abstract view of the Model-View-ViewModel pattern

An abstract view of the Model-View-ViewModel pattern

As mentioned, the MVVM pattern is particularly suited in WPF and Silverlight development because of the extremely powerful support for data binding. Figure 2 shows in more detail a MVVM application in WPF/Silverlight.

Figure 2: Practical schema of a MVVM implementation in WPF/Silverlight

Practical schema of a MVVM implementation in WPF/Silverlight

The markup in the XAML file defines all the details of the data binding. The data context is an instance of the ViewModel class. The code-behind class is extremely thin when not just empty. Typically, you set the data context to an instance of the view model class directly in the markup as shown below:

This sets a binding between UI elements and properties on the view model object. A method binding can be set directly in XAML using commands triggers. In this case, the code-behind class is just empty. In Silverlight this may require adding some code in the code-behind class to dispatch events to methods on view model class. The logic to interact with the middle tier is buried in the folds of the view model class.

A Quicker Way to Arrange the User Interface

The MVVM pattern is designed to model a piece of user interface around a use-case. Data-driven applications, however, often just need to edit and save a specific chunk of data. In other words, in data-driven applications the use-case is quite simple: edit/save some data. (See Figure 3.)

Figure 3: A simple use-case for editing/saving data.

A simple use-case for editing/saving data.

The code behind the View and Modify use-cases consists in displaying/editing the data retrieved from the database. The Holy Grail of data-driven software is an engine capable of producing a compelling and effective user interface from an object that looks a lot like a strongly typed wrapper around a table row. Frameworks such as Castle ActiveRecord exist to simplify the task and recently Microsoft approached the same way with Dynamic Data controls in ASP.NET 3.5 SP1.

An engine that automatically produces a user interface for displaying/editing data works well with the MVVM pattern. However, if all you need is editing a data type a rich visualization engine combined with an Adapter pattern is more than enough. Silverlight 3 comes with a new control—the DataForm control—through which you can design a view model around a data type in what actually results to be a specialization of the MVVM pattern.

The DataForm Control

The DataForm control is smart enough to analyze the public properties of its data source and generate some UI accordingly. For example, if you use the following class Person the DataForm will use text boxes for string properties, check boxes for Booleans, and a date picker control for dates.

In addition, the DataForm can switch between view and edit mode and supports binding to a collection of objects. In this case, it also provides navigation capabilities looking like the Silverlight’s counterpart of the popular Microsoft Access data navigator component. (See Figure 4.)

Figure 4: The DataForm control in action

The DataForm control in action

The DataForm control can be bound to a single data object or a collection. In the former case, you use the CurrentItem property; otherwise, you opt for the ItemsSource property. These properties can be set either programmatically or declaratively in the markup. The control is implemented in a separate assembly (System.Windows.Controls.Data.DataForm) but is listed in the Silverlight toolbox. Here’s the code you get once you have dropped a DataForm in a Silverlight page.

To display a record through the standard interface you just set the CurrentItem property:

If you go through the documentation of the control, you’ll find many other interesting properties including template properties for gaining full control over the header, footer, and item display. For the purpose of this article, though, I’ll be focusing on the characteristics of the data being edited through DataForm.

Editing Domain Entities

Direct editing of domain entities such as a Customer object is not necessarily a good idea. Not necessarily, in fact, a class layout that works for storage also works for display. Wherever possible, it would be preferable to use a wrapper object for any domain object to display/edit. The wrapper object will include some UI specific validation logic that may save you from roundtripping data to the server to ensure the object content is valid and acceptable. On the other hand, a view-only wrapper object is a sort of data-transfer object and, as such, it requires extra work to be arranged. This extra work may be quite a bit of work in projects with hundreds of entities and use-cases.

If you can afford using view-only objects for any domain entity to display/edit, then I suggest you just bind these objects to the DataForm. Next, you take care of “adapting” domain data to the view-only objects. Put another way, you first do a sort of data injection from the domain object into the view object. When the DataForm is dismissed, you retrieve data and inject it back into the original entity object.

Given a Customer object created using LINQ-to-SQL from the Northwind database, here’s a possible view object:

The CustomerViewModel class is a subset of the domain Customer type specifically created for the UI. In this case, it only contains a smaller set of properties. In addition, the CustomerViewModel class features a specific constructor and an extra method—Merge.

The constructor takes a domain object and copies its content into the view object. The Merge method does the reverse and saves edited data back into a given domain object. This data injection/ejection mechanism is needed to decouple domain and view objects.

When the user clicks to display a customer, the code-behind class will retrieve the requested customer and copy the content into a customer view object:

When the DataForm is dismissed (typically in the ItemEditEnded event), you eject values from the value object back into the original domain object.

Summary

The DataForm is an extremely rich control that enables interesting scenarios in Silverlight 3 data-driven development. This article just scratched the surface showing how to relate data displayed in the DataForm with the rest of a multi-tier system. In the next article, I’ll go through an end-to-end example showing how to retrieve data from a remote WCF service, edit locally, and save back. In doing so, I’ll touch on the MVVM pattern again and show other features of the DataForm such as its native support for data annotations on the view object. Stay tuned.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Dino Esposito

Dino Esposito is one of the world's authorities on Web technology and software architecture. Dino published an array of books, most of which are considered state-of-the-art in their respective areas. His most recent books are “Microsoft ® .NET: Architecting Applications for the Enterprise” and “...

This author has published 51 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Folder Dialog in Silverlight 4
Diptimaya Patra discusses the Folder Dialog in Silverlight 4.
Develop a Flexible 2.5D Scene Editor Targeting Silverlight RPG Games - Part 1
Starting from this article, I'm going to introduce to you an excellent 2.5D RPG games scene editor -...
Develop a Flexible 2.5D Scene Editor Targeting Silverlight RPG Games - Part 2
In this article, I'm going to introduce to you how to construct such a 2.5D RPG game scene editor th...
Displaying Notification Messages in a Silverlight Dashboard Application
In this article we will see how we could display a notification message and further a list of notifi...
Widget Refresh Timer in MVVM in Silverlight
In this article we'll see how to refresh and disable widgets using the Model View View-Model pattern...

You might also be interested in the following related blog posts


How to display data from different tables using one data source read more
Data-binding Telerik CoverFlow for Silverlight + some Routed Commands goodness read more
MVC or Web Forms? A Dying Question read more
BulletedList in Silverlight read more
Introducing Versatile DataSources read more
The Underground at PDC read more
November's Toolbox Column Now Online read more
Using WCF with SQL Azure and Telerik OpenAccess read more
Grouping data in a Silverlight DataGrid read more
Performance Gains and Enhanced HTML-like Support Brought to WinForms Applications with Q3 2009 Release read more
Top
 
 
 

Please login to rate or to leave a comment.