(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Creating Rich Data Forms in Silverlight - Introduction

(27 votes)
Boyan Mihaylov
>
Boyan Mihaylov
Joined Jul 18, 2008
Articles:   11
Comments:   12
More Articles
35 comments   /   posted on Apr 23, 2009

This article is compatible with the latest version of Silverlight.


Introduction

Silverlight has introduced easily creating and manipulating rich data forms. These series of posts will help you when creating rich data forms in Silverlight in your projects. Silverlight introduces a new control, called DataForm. It enables various methods for display, edit, update and navigation through data.

The DataForm control is like the DataGrid control in Silverlight 2. But while the DataGrid control is used to manipulate a list of items, the DataForm control focuses on the item itself.

In this article I will show you the basics of the DataForm control – what you can do with it and why you should use it. I will show you how you can bind an item or a collection of items to a data form. Microsoft guys have done a great job with this control, so there are many features that you can use directly without much pain.

You can run the online demo before you read the article just to see what it is.

Beginning

Let’s create a new Silverlight application and call it DataFormTest.

In order to use the DataForm control, we have to add a reference to System.Windows.Controls.Data.DataForm assembly in our project. Then in the XAML declaration of the main page you should add a new namespace in order to access this assembly. Your XAML will look like this:

<UserControl x:Class="DataFormTest.MainPage" 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  xmlns:df="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm" 
  Width="400" Height="300"
    … 
</UserControl> 

Now you can add the DataForm control.

<df:DataForm x:Name="myDataForm" /> 

One-Item Binding

Well, we have our DataForm control in our project. Now, let’s learn how to expose its features. Let’s create a simple class, which we will bind to our DataForm control. I will call this class Movie. It represents a movie in the real life. Here is its declaration:

public enum Genres 
  Comedy, 
  Fantasy, 
  Drama, 
  Thriller 
 
public class Movie 
  public int MovieID { getset; } 
  public string Name { getset; } 
  public int Year { getset; } 
  public DateTime AddedOn { getset; } 
  public string Producer { getset; } 
  public Genres Genre { getset; } 

Now in the Loaded event of our UserControl we can create a new Movie object and bind it to the DataForm control like this:

Movie movie = new Movie(); 
… 
myDataForm.CurrentItem = movie; 

When you build the project and start it, you will see it all in action.

Great! You have a data form with fields which correspond to the properties of your class with minimal efforts. Now the form is read-only so you cannot change anything. In order to make changes, you have to click the button in the right top corner (the pencil).

When clicking the pencil, you go in edit mode. You can make changes to each of the fields. If your field is of type DateTime, you can change its value by selecting a date from the calendar. Isn’t this cool? So, you edit the data of the object and press the Save button. The changes are successfully committed. But what if you type illegal characters in a field of type integer?

If you enter invalid data in some of the fields, you will get a validation summary, which shows the errors. In this case you are not able to save the changes until you don't fix the problems. If you position your mouse on the small red triangle in the upper right corner of a field, which has an error, you will see the error message.

Multiple-Items Binding

We saw how we can bind an item to the DataForm control. But this is just a simple case. You can bind a collection of items and navigate through them. Let’s create our own collection, which will represent a set of movies.

public class MoviesCollection : ObservableCollection<Movie> { … } 

We use ObservableCollection, because it inherits from INotifyCollectionChanged and INotifyPropertyChanged. The second interface is used when you want your object (of a specific type) to notify for each change of its properties. This interface is commonly used when you want to make your object bindable.

In the Loaded event of the UserControl we will bind an instance of our collection to the DataForm control.

myDataForm.ItemsSource = Repository.GetMovies();

Repository is a simple class with one static method, which returns a collection of movies. When you build and run you get the following screen.

New buttons have been added in the top bar of the form. You have buttons which let you navigate through each of the movies. You can edit each of them, too. Even more, you can add or delete movies with one click. Well, you have fully functional data form with almost no efforts. Everything is built-in the DataForm control.

Now, let’s have a look over the properties of the DataForm control. I bet that Microsoft have put something interesting there, which can help us modify the form to suit our application more and more.

Events

  • AddingItem - occurs just before an item is added to the collection
  • DeletingItem – occurs just before an item is deleted
  • BeginningEdit – occurs when you begin to edit an item
  • ItemEditEnding – occurs just before an item (which is being edited) is saved
  • ItemEditEnded – occurs just after an item (which has been edited) is saved
  • CurrentItemChanged – occurs when you change the selected item (like SelectionChanged in a ListBox control)
  • ValidatingItem – occurs when we are validating an item

Properties

  • AutoCommit – indicates whether to save the changes if the user presses the next (or the previous) button without pressing the Save button
  • AutoEdit – indicates whether to go into Edit mode automatically when you select a record
  • CancelButtonContent – lets the user set a content for the Cancel button
  • CommitButtonContent – lets the user set the content for the Commit button
  • CanUserAddItems – determines whether the user can add new items or not
  • CanUserDeleteItems – determines whether the user can delete an existing item or not
  • DescriptionViewerPosition – sets the position of description (each field may have a description, but we will see this in the following part of these series of posts)
    • Auto
    • BesideContent
    • BesideLabel
  • FieldLabelPosition – sets the position of labels for fields
    • Auto - automatically chooses the best position
    • Left - default, places the labels on the left side of the fields
    • Top - places the labels over the fields
  • Header – sets the header of the form
  • AutoGenerateFields – indicates whether fields should be automatically generated or not. In the next article of these series of articles I will show you how you can manipulate the style of a DataForm control.

In Action

Now, let’s see the data form in action with some modifications made to its properties.

<df:DataForm x:Name="myDataForm" 
CancelButtonContent="Cancel Me!" CommitButtonContent="Save Me!" 
AutoCommit="False" AutoEdit="False" FieldLabelPosition="Top" 
Header="My First Rich Data Form" CanUserDeleteItems="False"/> 

You can see, there is no Delete button, because we set CanUserDeleteItems to false. When you are editing an item, you cannot navigate through other items, because AutoCommit is set to false. If AutoEdit is set to true, you will immediately go in edit mode when you “open” an item. Now, labels are positioned over the fields, because we changed the FieldLabelPosition property.

But there is something strange. We have set a property, called CancelButtonContent, but such a button does not exist. Actually, a cancel button exists, but you have to make your class (Movie in our case) derive from an interface, called IEditableObject. This interface enables your class to respond to specific edit events via public methods -BeginEdit, CancelEdit and EndEdit. I will tell you more about this interface in the next article of these series of articles.

Conclusion

The DataForm control is a perfect solution for your application if you want to let the user manipulate a collection of data, focusing on each item. The DataForm control will save you a lot of time, because it has all of the necessary features to let you show and manipulate data collections.

In your projects you may need to change the style of the DataForm to fit your own application. You will ask, “How to do this?” Well, there is a very simple solution to your problem. The DataForm control supports template properties (such as HeaderTemplate, DisplayTemplate, EditTemplate and InsertTemplate). In my next article I will show you how you can manipulate these properties in order to change the structure of the control. I will also show you how to style your data form controls in order to make them fit better in your applications.

In the third article of these series of articles I will show you how to validate your data to achieve better results. You can specify on your class (this is the Movie class in our case) different attributes to tell the DataForm control how to validate each of its properties. This feature is very powerful and you will see it in action in one of the next articles.

Source Code

The source code is available for you free of charge. You can download the source code for all of the examples and check it by yourself.

References

  • http://silverlight.net/learn/learnvideo.aspx?video=187317
  • http://pendsevikram.blogspot.com/2009/03/silverlight-3-dataform-control-features.html
  • http://microapplications.com/blog/archive/2009/03/27/328.aspx

Subscribe

Comments

  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Josh on Apr 23, 2009 10:17
    Thanks for the tutorial! I didn't know this existed in Silverlight 3.
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Cris on Apr 23, 2009 18:34
    And how can we customize the labels? or even the error messages? any thought about it?
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Jared Thaler on Apr 24, 2009 00:36
    Very Nice.

    While, unfortunately, this will be next to useless for my main program (the user interface is vastly more complex than this would appear to natively support.)  It should cut dev time on the Admin Backend by at least a quarter.

  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Jared Thaler on Apr 24, 2009 02:55
    Also, while Observable Collections are nice, is it possible to make this work with a Dictionary<> Type?

     

    (For that matter, has anyone worked out an "Observable Dictionary" Type?)


  • boyanmihailov

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by boyanmihailov on Apr 24, 2009 03:08

    @Cris: You can customize everything :) In my next articles I will show you how you can change the entire style of the control and how you can specify your own validation rules and messages.

    @Jared: It depends on your necessities. The DataForm control gives you a lot built-in features. You can change everything of its UI. I have not worked with "Observable Dictionary", but here is what I found - http://social.msdn.microsoft.com/forums/en-US/wpf/thread/2ec0c111-0682-49c8-a9d8-ae374328ea2e/

  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Waqas on May 05, 2009 10:39
    Hey Jarred: Did you try this:

    ObservableCollection<Dictionary<int, string>> collection = new ObservableCollection<Dictionary<int, string>>();

    dataForm.ItemsSource = collection;


  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Keith on May 08, 2009 16:37
    AMAZING !
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Richard on May 20, 2009 14:29
    Nice, simple example without window dressing.   Congrats!
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Satish on Jul 15, 2009 14:23
    Is there is a way in Dataform to specify the control (Custom control instead of standard textbox control for a string property) of my choice, that would be created dynamically for each of the property?
  • boyanmihailov

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by boyanmihailov on Jul 15, 2009 21:08
    @Satish: Yes, you can. You can see my article about customizing DataForm control - http://www.silverlightshow.net/items/Creating-Rich-Data-Forms-in-Silverlight-3-Customization.aspx
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Satish on Jul 16, 2009 12:29

    @boyanmihailov: Sorry, I could n't trace my requirement in the URL : http://www.silverlightshow.net/items/Creating-Rich-Data-Forms-in-Silverlight-3-Customization.aspx.

    Reiterating my requirement: We use custom controls in our aplication. Hence, every string data must be displayed  using our own Text control (NOT using Silverlight control). Similarly every date time fields must be bound to our custom datetime control.

    Is there a way to achieve this. Kindly help with source code if possible.

  • boyanmihailov

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by boyanmihailov on Jul 16, 2009 19:30
    @Satish: Look at the part Customizing DataForm Fields. You can use DataFormTemplateField field to create your own display & edit fields. For each custom field you define a DataTemplate so you can place your custom controls in it.
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Mark on Jul 24, 2009 03:16
    What about a passwordBox?  Can you do this with DataForms??
  • boyanmihailov

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by boyanmihailov on Jul 24, 2009 20:56
    @Mark: Sure! You can use whatever control in a field
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Mark on Jul 28, 2009 08:46
    I can't seem to get the add item "+" button to be enabled.  The "+" icon is visible but it's always grayed out.  My ItemsSource is set to an ObservableCollection and the delete icon "-" isn't gray and works.  I'm not using the Beta.  Anyone else having this problem?

     


  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Mark on Aug 01, 2009 00:20
    I've found out that if you don't have a default constructor for the class record bounded to the dataform ItemSource the "+" icon add button will never be enabled. 
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Abhinay on Aug 03, 2009 13:04
    Hi,

    Can we add dynamically user control instead of statically defining it in to Data Template in XAML code.

    Thanks,

    Abhinay Agrawal.
  • boyanmihailov

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by boyanmihailov on Aug 03, 2009 20:24
    @Abhinay: You can see this topic http://silverlight.net/forums/t/115097.aspx
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Nishad on Aug 04, 2009 09:58
    This helped me a lot
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Marcw on Aug 05, 2009 12:37
    Thanks for the post, very useful.

    Now I am trying to include lookup capabilities for reference data in my model. So with your example of the movie you also have a genre, in this example it's probably an enum, but potentially it is another domain entity with its own form to manage the genres. Does the dataform control include the ability to have this reference data included as either a dropdown list or as a lookup control in order to select a value from the reference entity? I understand that I could customize the template to include this, but it would be time saving if this were built into the control. ASP Dynamic Data has this feature.

    Any comment will be useful


  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Bogdan on Aug 13, 2009 11:17

    Nice introduction, thumbs up!

    Worth mentioning, this code needs some adjustements in order to make it work with the latest release of the Silverlight Tookit. Some attributes names have changed - see here: http://silverlight.net/forums/p/109581/258546.aspx. Also, a nice enhancement of the new out-of-the-box DataForm is that it now automatically places a combobox to edit the values taken from an Enum (Genere), instead of a textbox, like it was the case with the old version.

  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Dan on Oct 27, 2009 22:05

    Why don't I see Windows.system.Controls.Data.DataForm Dll when I try to add a reference to it?  All of the other .Data Dlls are there.  They are all under C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client.

     

     

  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Dan on Oct 27, 2009 22:06

    Why don't I see Windows.system.Controls.Data.DataForm Dll when I try to add a reference to it?  All of the other .Data Dlls are there.  They are all under C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client.

     

     

  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Aleksey K on Nov 12, 2009 20:04
    I cannot find System.Windows.Controls.Data.DataForm.dll anywhere. I have downloaded SL 3 as well as toolkit and ran a search on my c drive and it found no file with that name. 
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by xxx on Nov 23, 2009 15:41
    try System.Windows.Controls.Data.DataFormToolkit.dll
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by gep13 on Dec 01, 2009 15:42
    When I try to use the System.Windows.Controls.Data.DataFormToolkit.dll rather than the System.Windows.Controls.Data.DataForm.dll I no longer have access to the .Fields property of the DataForm, which is used for customization of the DataForm.  Any ideas?
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Murali on Dec 08, 2009 16:34
    Good article.
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by jose flores on Dec 15, 2009 19:16
    Very grateful for the tutorial
  • -_-

    RE: Creating Rich Data Forms in Silverlight 3 - Introduction


    posted by Josemar on Apr 13, 2010 15:40
    Good article! I have a problem you can help me. How do I customize the buttons DataForm? I have to change the icons of DataForm for custom icons.
  • -_-

    fails to validate and save


    posted by Gideon on Oct 10, 2010 00:32

    Big SNAG!!

    if you say dataform.CurrentItem = obj; and obj is of type private class, the form acts weird! It shows the fields but doesn't save or show validation errors!

  • lnikolov

    RE: Creating Rich Data Forms in Silverlight - Introduction


    posted by lnikolov on Feb 06, 2011 17:22
    The article has been updated to the latest version of Silverlight and Visual Studio.
  • -_-

    form.show() in Silverlight


    posted by Nidhi Shah on Feb 19, 2011 11:36
    private void LoanCalculationButton_Click(object sender, RoutedEventArgs e) { LoanCalculation loanCalculation = new LoanCalculation(); loanCalculation.Show(); }
  • RicardoMiquilarenaUrrutia

    Re: Creating Rich Data Forms in Silverlight - Introduction


    posted by RicardoMiquilarenaUrrutia on Jun 02, 2011 23:34

    Good job, I read another article and created a Data Form from it, but this one allowed me to understand how it actually works,,, Thanks!

    If there a way to place the field label in top for an individual field?

    Can the DescriptionViewer be on at all times?

  • jeriani

    Re: Creating Rich Data Forms in Silverlight - Introduction


    posted by jeriani on Dec 14, 2012 17:14

    Hello,

    I do maintenance in a Silvelight 4 web application that use dataform.
    I mainly use dataform AutoGenerateFields="True" and its works well.
    But with comboBox I need to define wether I want a default value or not. The combobox seem to be " mandatory", cause when I select the empty value et validate the form  the validation/exception msg "Input is not in the correct format is diplayed" in red.

    Is there a way to allow null value and avoid "Input is not in the correct format" message?

    Thanks in advance

    JEROME

  • jeriani

    Re: Creating Rich Data Forms in Silverlight - Introduction


    posted by jeriani on Dec 14, 2012 18:59

    Hello,

    I do maintenance in a Silvelight 4 web application that use dataform.
    I mainly use dataform AutoGenerateFields="True" and its works well.
    But with comboBox I need to define wether I want a default value or not. The combobox seem to be " mandatory", cause when I select the empty value et validate the form  the validation/exception msg "Input is not in the correct format is diplayed" in red.

    Is there a way to allow null value and avoid "Input is not in the correct format" message?

    Thanks in advance

    JEROME

Add Comment

Login to comment:
  *      *