Working with DataForm in Microsoft Silverlight 4

Exclusive offer: get 50% off this eBook here
Microsoft Silverlight 4 Data and Services Cookbook

Microsoft Silverlight 4 Data and Services Cookbook — Save 50%

Over 80 practical recipes for creating rich, data-driven business applications in Silverlight with this Microsoft book and eBook

€28.99    €14.50
by Gill Cleeren Kevin Dockx | May 2010 | Microsoft

In this article by Gill Cleeren and Kevin Dockx, authors of Microsoft Silverlight 4 Data and Services Cookbook, we will cover the following recipes:

  • Displaying and editing an object using the DataForm
  • Displaying and editing a collection using the DataForm
  • Validating the DataForm

Displaying and editing an object using the DataForm

Letting a user work with groups of related data is a requirement of almost every application. It includes displaying a group of people, editing product details, and so on. These groups of data are generally contained in forms and the Silverlight DataForm (from the Silverlight Toolkit) is just that—a form.

In the next few recipes, you'll learn how to work with this DataForm. As of now, let's start off with the basics, that is, displaying and editing the data.

Getting ready

For this recipe, we're starting with a blank solution, but you do need to install the Silverlight Toolkit as the assemblies containing the DataForm are offered through this. You can download and install it from http://www.codeplex.com/Silverlight/. You can find the completed solution in the Chapter05/Dataform_DisplayAndEdit_Completed folder in the code bundle that is available on the Packt website.

How to do it...

We're going to create a Person object, which will be displayed through a DataForm. To achieve this, we'll carry out the following steps:

  1. Start a new Silverlight solution, name it DataFormExample, and add a reference to System.Windows.Controls.Data.DataForm.Toolkit (from the Silverlight Toolkit). Alternatively, you can drag the DataForm from the Toolbox to the design surface.
  2. Open MainPage.xaml and add a namespace import statement at the top of this fi le (in the tag) as shown in the following code. This will allow us to use the DataForm, which resides in the assembly that we've just referenced.

    xmlns:df="clr-namespace:System.Windows.Controls;
    assembly=System.Windows.Controls.Data.DataForm.Toolkit"
  3. Add a DataForm to MainPage.xaml and name it as myDataForm. In the DataForm, set AutoEdit to False and CommandButtonsVisibility to All as shown in the following code:
    <Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
    <RowDefinition Height="40" ></RowDefinition>
    <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <TextBlock Text="Working with the DataForm"
    Margin="10"
    FontSize="14" >
    </TextBlock>
    <df:DataForm x:Name="myDataForm"
    AutoEdit="False"
    CommandButtonsVisibility="All"
    Grid.Row="1"
    Width="400"
    Height="300"
    Margin="10"
    HorizontalAlignment="Left"
    VerticalAlignment="Top" >
    </df:DataForm>
    </Grid>
  4. Add a new class named Person to the Silverlight project having ID, FirstName, LastName, and DateOfBirth as its properties. This class is shown in the following code. We will visualize an instance of the Person class using the DataForm.
    public class Person
    {
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    }
  5. Open MainPage.xaml.cs and add a person property of the Person type to it. Also, create a method named InitializePerson in which we'll initialize this property as shown in the following code:
    public Person person { get; set; }
    private void InitializePerson()
    {
    person = new Person()
    {
    ID = 1,
    FirstName = "Kevin",
    LastName = "Dockx",
    DateOfBirth = new DateTime(1981, 5, 5)
    };
    }
  6. Add a call to InitializePerson in the constructor of MainPage.xaml.cs and set the CurrentItem property of the DataForm to a person as shown in the following code:
    InitializePerson();
    myDataForm.CurrentItem = person;
  7. You can now build and run your solution. When you do this, you'll see a DataForm that has automatically generated the necessary fields in order to display a person. This can be seen in the following screenshot:

How it works...

To start off, we needed something to display in our DataForm: a Person entity. This is why we've created the Person class: it will be bound to the DataForm by setting the CurrentItem property to an object of type Person.

Doing this will make sure that the DataForm automatically generates the necessary fi elds. It looks at all the public properties of our Person object and generates the correct control depending on the type. A string will be displayed as a TextBox, a Boolean value will be displayed as a CheckBox, and so on.

As we have set the CommandButtonsVisibility property on the DataForm to All, we get an Edit icon in the command bar at the top of the DataForm. (Setting AutoEdit to False makes sure that we start in the display mode, rather than the edit mode). When you click on the Edit icon, the DataForm shows the person in the editable mode (using the EditItemTemplate) and an OK button appears. Clicking on the OK button will revert the form to the regular displaying mode. Do keep in mind that the changes you make to the person are persisted immediately in memory (in the case of a TextBox, when it loses focus).

If necessary, you can write extra code to persist the Person object from the memory to an underlying datastore by handling the ItemEditEnded event on the DataForm.

There's more...

At this moment, we've got a DataForm displaying a single item that you can either view or edit. But what if you want to cancel your edit? As of now, the Cancel button appears to be disabled. As the changes you make in the DataForm are immediately persisted to the underlying object in the memory, cancelling the edit would require some extra business logic. Luckily, it's not hard to do.

First of all, you'll want to implement the IEditableObject interface on the Person class, which will make sure that cancelling is possible. As a result, the Cancel button will no longer be disabled. The following code is used to implement this:

public class Person : IEditableObject
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public void BeginEdit()
{}
public void CancelEdit()
{}
public void EndEdit()
{}
}

This interface exposes three methods: BeginEdit, CancelEdit, and EndEdit. If needed, you can write extra business logic in these methods, which is exactly what we need to do. For most applications, you might want to implement only CancelEdit, which would then refetch the person from the underlying data store. In our example, we're going to solve this problem by using a different approach. (You can use this approach if you haven't got an underlying database from which your data can be refetched, or if you don't want to access the database again.) In the BeginEdit method, we save the current property values of the person. When the edit has been cancelled, we put them back to the way they were before. This is shown in the following code:

public void BeginEdit()
{
// save current values
tmpPerson = new Person()
{
ID = this.ID,
FirstName = this.FirstName,
LastName = this.LastName,
DateOfBirth = this.DateOfBirth
};
}
public void CancelEdit()
{
// reset values
ID = tmpPerson.ID;
FirstName = tmpPerson.FirstName;
LastName = tmpPerson.LastName;
DateOfBirth = tmpPerson.DateOfBirth;
}

Now, cancelling an edit is possible and it actually reverts to the previous property values.

More on DataForm behavior

The DataForm exposes various events such as BeginningEdit (when you begin to edit an item), EditEnding (occurs just before an item is saved), and EditEnded (occurs after an item has been saved). It also exposes properties that you can use to defi ne how the DataForm behaves.

Validating a DataForm or a DataGrid

As you might have noticed, the DataForm includes validation on your fields automatically. For example, try inputting a string value into the ID field. You'll see that an error message appears. This is beyond the scope of this recipe, but more on this will be discussed in the Validating the DataForm recipe.

Managing the editing of an object on different levels

There are different levels of managing the editing of an object. You can manage this on the control level itself by handling events such as BeginningEdit or ItemEditEnded in the DataForm. Besides that, you can also handle editing on a business level by implementing the IEditableObject interface and providing custom code for the BeginEdit, CancelEdit, or EndEdit methods in the class itself. Depending on the requirements of your application, you can use either of the levels or even both together.

See also

In this recipe, we've seen how the DataForm is created automatically. For most applications, you require more control over how your fi elds, for example, are displayed. The DataForm is highly customizable, both on a template level (through template customization) and on how the data is generated (through data annotations). If you want to learn about using the DataForm to display or edit a list of items rather than just one, have a look at the next recipe, Displaying and editing a collection using the DataForm.

Displaying and editing a collection using the DataForm

In the previous recipe, you learned how to work with the basic features of the DataForm. You can now visualize and edit an entity. But in most applications, this isn't enough. Often, you'll want to have an application that shows you a list of items with the ability to add a new item or delete an item from the list. You'll want the application to allow you to edit every item and provide an easy way of navigating between them. A good example of this would be an application that allows you to manage a list of employees.

The DataForm can do all of this and most of it is built-in. In this recipe, you'll learn how to achieve this.

Getting ready

For this recipe, we're starting with the basic setup that we completed in the previous recipe. If you didn't complete that recipe, you can find a starter solution in the Chapter05/ Dataform_Collection_Starter folder in the code bundle that is available on the Packt website. The finished solution for this recipe can be found in the Chapter05/Dataform_ Collection_Completed folder.

In any case, you'll need to install the Silverlight Toolkit as the assemblies containing the DataForm are offered through it. You can download and install it from http://www.codeplex.com/Silverlight/.

Microsoft Silverlight 4 Data and Services Cookbook Over 80 practical recipes for creating rich, data-driven business applications in Silverlight with this Microsoft book and eBook
Published: April 2010
eBook Price: €28.99
Book Price: €46.99
See more
Select your format and quantity:

How to do it...

We're going to create an application that visualizes a list of people using the DataForm. In order to achieve this, carry out the following steps. (If you're starting from a blank solution, you'll need to add a DataForm to your MainPage and create a Person class having ID, FirstName, LastName, and DateOfBirth as its properties.)

  1. Open MainPage.xaml.cs and add a new property called lstPerson of the ObservableCollection type of Person to it. This is shown in the following line of code:
    public ObservableCollection<Person> lstPerson { get; set; }
  2. Create a new method called InitializePersons(), which is used to initialize lstPerson. This is shown in the following code:
    private void InitializePersons()
    {
    lstPerson = new ObservableCollection<Person>()
    {
    new Person()
    {
    ID=1,
    FirstName="Kevin",
    LastName="Dockx",
    DateOfBirth = new DateTime(1981, 5, 5)
    },
    new Person()
    {
    ID=2,
    FirstName="Gill",
    LastName="Cleeren",
    DateOfBirth = new DateTime(2009, 1, 1)
    },
    new Person()
    {
    ID=3,
    FirstName="Judy",
    LastName="Garland",
    DateOfBirth = new DateTime(1922, 6, 10)
    }
    };
    }
  3. In the MainPage constructor, call the InitializePersons() method and set the ItemsSource property of myDataForm to lstPerson as shown in the following code:

    public MainPage()
    {
    InitializeComponent();
    InitializePersons();
    myDataForm.ItemsSource = lstPerson;
    }
  4. You can now build and run the solution. You'll notice that you can navigate through the list of persons in the DataForm by using the navigation buttons at the top of the DataForm. This can be seen in the following screenshot:

How it works...

In the previous recipe, we set the CurrentItem property of the DataForm to a Person object. This recipe builds on that, but instead of setting the CurrentItem property, we bind the ItemsSource property to our ObservableCollection of Person. While doing this, the DataForm will automatically generate navigation buttons to navigate through the collection and will also generate an Add and a Delete button. In order to access the current item, you can refer to the CurrentItem property, which will change automatically while navigating through the list.

There's more...

In order to change the behavior of the DataForm, you can set a variety of its properties on the DataForm. AutoCommit makes sure changes are saved if the user navigates through the list without clicking on the OK button, while AutoEdit makes sure the DataForm automatically goes in Edit mode when the user selects a record. CancelButtonContent sets the content for the Cancel button. (You need to implement IEditableObject on your Person class for this button to be enabled. Have a look at the previous recipe for more information on this.) CommitButtonContent sets the content for the OK button.

In order to change the ability to add or delete items, you can easily change the CommandButtonsVisibility property to show or hide the corresponding buttons.

Along with that, the DataForm exposes a few events specifi cally for use while binding to collections. AddingNewItem is fi red just before an item is added to the collection, DeletingItem is fi red just before an item is deleted, and CurrentItemChanged is fi red when the current item has been changed (which happens when you navigate through the list of items, or when you add or delete an item).

See also

In this recipe, we've used an ObservableCollection that is bound to the ItemsSource property of the DataForm.

For most applications, you'll require more control over how your fields (for example) are displayed. The DataForm is highly customizable, both on a template level (through template customization) and on how the data is generated (through Data Annotations).

Validating the DataForm

Validation of your data is a requirement for almost every application to make sure that no invalid input is possible. If you're using a DataForm, you can easily implement validation by using Data Annotations on your classes or properties. This control picks up these validation rules automatically and even provides visual feedback. In this recipe, you'll learn how to implement this kind of validation for a DataForm.

Getting ready

We're starting from the solution that we competed in the Displaying and editing a collection using the DataForm recipe. If you didn't complete that recipe, you can fi nd a starter solution located in the Chapter05\Dataform_Validation_Starter folder in the code bundle that is available on the Packt website. The finished solution for this recipe can be found in the Chapter05\Dataform_Validation_Completed folder.

In any case, you'll need to install the Silverlight Toolkit as the assemblies containing the DataForm are offered through it. You can download and install it from http://www.codeplex.com/Silverlight/.

How to do it...

If you're starting from a blank solution, you'll need to add a DataForm to your MainPage and create a Person class having ID, FirstName, LastName, and DateOfBirth as its properties. The DataForm on the MainPage should be bound to an ObservableCollection of Person.

We're going to make sure that the DataForm reacts to the validation attributes we'll add to the Person class. To achieve this, carry out the following steps:

  1. Add a reference to System.ComponentModel.DataAnnotations in your Silverlight project.
  2. Open the Person class and add the following attributes to the FirstName property of this class:

    [StringLength(30, MinimumLength=3,
    ErrorMessage="First name should have between 3 and 30
    characters")]
    [Required(ErrorMessage="First name is required")]
    public string FirstName { get; set; }
  3. We can now build and run our solution. When you enter invalid data in the FirstName field, you notice that you get visual feedback for these validation errors and you aren't able to persist your changes unless they are valid. This can be seen in the following screenshot:

How it works...

We've added Data Annotations such as the RequiredAttribute and the StringLengthAttribute to the FirstName property in the Person class. These Data Annotations respectively tell any control that can interpret them that the FirstName is required and it should have between 3 and 30 characters. We've also added a custom error message for both the Data Annotations by fi lling out the ErrorMessage NamedParameter.

As a DataForm is able to look for these validation rules automatically, it will show validation errors if the validation fails. This feature comes out of the box with a DataForm, without you having to do any of the work. Therefore, you can easily enable validation by just using Data Annotations.

By using named parameters in the constructors of your attributes, you can further customize how the attribute should behave. For example, ErrorMessage enables you to customize the message that is shown when validation fails.

There's more...

In this recipe, we've used just a few of the possible data annotations. DataTypeAttribute, RangeAttribute, RegularExpressionAttribute, RequiredAttribute, StringLengthAttribute, and CustomValidationAttribute are all of the data annotations at your disposal.

For all of these attributes, named parameters are possible in order to further customize the way validation should occur. ErrorMessage, ErrorMessageResourceName, and ErrorMessageResourceType are available on all attributes, but many more are available depending on the attribute you use. You can check them by looking at the IntelliSense tooltip you get on the attribute constructor.

Other uses of Data Annotations

In the other recipes of this article, you've already noticed that other non-validating data attributes exist such as the display attributes and the mode attributes. These attributes are used to control how certain information should be displayed or how certain properties should relate to each other

RIA Services and Data Annotations

Data Annotations are heavily used in combination with WCF RIA Services.

Summary

In this article, we learnt:

  • Displaying and editing an object using the DataForm
  • Displaying and editing a collection using the DataForm
  • Validating the DataForm

If you have read this article you may be interested to view :

Microsoft Silverlight 4 Data and Services Cookbook Over 80 practical recipes for creating rich, data-driven business applications in Silverlight with this Microsoft book and eBook
Published: April 2010
eBook Price: €28.99
Book Price: €46.99
See more
Select your format and quantity:

About the Author :


Gill Cleeren

Gill Cleeren is Microsoft Regional Director (http://www.theregion.com), Silverlight MVP (former ASP.NET MVP) and Telerik MVP. He lives in Belgium where he works as .NET architect at Ordina (http://www.ordina.be/). Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and training on new as well as existing technologies, such as Silverlight, ASP.NET and WPF at conferences including TechEd Berlin 2010, TechDays Belgium – Switzerland - Sweden, DevDays NL, NDC Oslo Norway, DevReach Bulgaria, NRW Conference Germany, Spring Conference UK, Telerik Silverlight Roadshow in Sweden, Telerik RoadShow UK. He is the author of Packt’s Microsoft Silverlight 4 Data and Services Cookbook and is also the author of many articles in various developer magazines and for SilverlightShow.net and he organizes the yearly Community Day event in Belgium. He also leads Visug (http://www.visug.be), the largest .NET user group in Belgium. You can find his blog at http://www.snowball.be and on Twitter by following @gillcleeren.

Kevin Dockx

Kevin Dockx lives in Belgium and works at RealDolmen, one of Belgium's biggest ICT companies, where he is a 30-year old technical specialist/project leader on .NET web applications, mainly Silverlight, and a solution manager for Rich Applications (Silverlight, Windows Phone 7, WPF, Surface, HTML5). His main focus is on all things Silverlight, but he still keeps an eye on the new developments concerning other products from the Microsoft .NET (Web) Stack. As a Silverlight enthusiast, he's a regular speaker on various national and international events, like Microsoft DevDays in the Netherlands, Microsoft Techdays in Portugal, NDC Oslo Norway, and Community Day Belgium. He is the author of Packt’s Microsoft Silverlight 4 Data and Services Cookbook and also writes articles for various Silverlight-related sites & magazines. His blog, which contains various tidbits on Silverlight, .NET, and the occasional rambling, can be found at http://blog.kevindockx.com/, and you can find him on Twitter as well: @KevinDockx.

Books From Packt

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide
Microsoft Silverlight 4 Business Application Development: Beginner’s Guide

SOA Patterns with BizTalk Server 2009
SOA Patterns with BizTalk Server 2009

ASP.NET MVC 1.0 Quickly
ASP.NET MVC 1.0 Quickly

Programming Microsoft Dynamics NAV 2009
Programming Microsoft Dynamics NAV 2009

VSTO 3.0 for Office 2007 Programming
VSTO 3.0 for Office 2007 Programming

Microsoft Dynamics AX 2009 Programming: Getting Started
Microsoft Dynamics AX 2009 Programming: Getting Started

Least Privilege Security for   Windows 7, Vista, and XP
Least Privilege Security for Windows 7, Vista, and XP

Learning SQL Server 2008 Reporting Services
Learning SQL Server 2008 Reporting Services

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software