Click here to Skip to main content
Click here to Skip to main content

Step-by-Step Using ImplicitDataTemplate in Silverlight 5 Beta

By , 8 May 2011
Rate this:
Please Sign up or sign in to vote.

Introduction

ImplicitDataTemplate is a new feature in Silverlight 5. Using ImplicitDataTemplate, you can declare multiple Data Templates for your control and based on the data type, you can load the proper data template automatically.

In this article, we will discuss on the same step by step with a good example. Read the complete article to know it in depth. If you have any queries, let me know. Feedback is always appreciated.

Let's do a quick analysis of what we want to achieve to showcase this feature. Assume we have an organization where we have Employees as well as Customers who are related to the organization. Now, we need to store records of both employees and customers. At the end, we need to display the records showing them in a proper way.

To demonstrate, we will create a ListBox and there we will mention whether the person is an employee or a customer. This simple example will help you to understand the feature very easily.

Prerequisites

Before starting with the rest of the topic, you need to set up your development environment. You need Visual Studio 2010 with SP1, Silverlight 5 Beta Tools for Visual Studio 2010. Later, you need to create a new Silverlight project.

Find the below posts which will answer all your queries and help you to set up your prerequisite:

  1. Install Silverlight 5 Beta in your development environment. You can install it side-by-side with the existing Silverlight versions
  2. New to Silverlight 5? This post will help you to Create your first Silverlight 5 project.

Once your dev environment is set up properly, jump to the next step to start discussing the main topic. Don't forget to ask your queries at the end of the articles.

Setting up the Solution

Before I start describing the feature with an step-by-step example, we need to set up the solution in proper way. Once you created the project, create the directory structure in MVVM way. Remember that MVVM structure is not required to use this feature but I prefer working in MVVM pattern.

In the solution explorer, first create the folder structure. For our MVVM based sample, we will create "Models", "Views", "ViewModels" and "Services" folder as shown below:

image

Once your folder structure is done, let's create the classes and XAMLs in the proper location. Add MainView.xaml in Views folder, MainViewModel.cs in ViewModels folder, DataService.cs in Services folder and an interface called IPerson.cs in the Models folder. Now create two classes named "Customer.cs" and "Employee.cs" in the same Models folder and implement them from the IPerson interface. Expose some properties in IPerson interface and implement them in both Customer and Employee classes.

image

Once done, build your project and fix the issues that you encountered.

Interface Implementation

Let's declare some properties named Firstname, Lastname and Age in the interface. Here is the implementation of the same:

image

You can download the interface file from here: IPerson.cs.

Model Implementation

Once the interface is ready, let's implement the interface properties in our contract classes too. They will look as below:

image

image

You can download the contract classes from here: Employee.cs and Customer.cs.

Implementing the DataService

You need a DataService to return the Person details. A person may be an Employee or a Customer. Assume that we are fetching it from database in this step and returning to the client. Here we will hard code the collection and return it back. We added few Employees and few Customers in the collection. As the base interface is IPerson for both the classes, we can easily add them in the collection. Find the code snippet here:

image

For your reference, you can download the DataService class from here: DataService.cs.

Implementing the ViewModel

Let us start coding on the ViewModel. Implement the INotifyPropertyChanged interface in it, so that, once any property changes, it will notify the view automatically to refresh the same. Now create a property named "Persons" of type ObservableCollection<IPerson> as shown below. In the constructor, call the GetPersons() method of DataService and store the data records in the property named "Persons".

image

You may want to download the MainViewModel.cs file. Download it from here: MainViewModel.cs

View Implementation

It's time to create the view and bind the collection to a listbox. First of all, add the namespaces of Model and ViewModel as shown below. We need to use them while binding data. Now, in the UserControl.Resources, add the MainViewModel as a StaticResource.

image

Add a ListBox and set the DataContext of the ListBox to the MainViewModel instance. Also, bind the ItemsSource property of the ListBox to the Persons collection which is present in the MainViewModel.

Here is how we created it:

image

Once done, build your project once again and fix the errors if any.

Creating DataTemplate in Older Way

Let us think in the older way of DataBinding using the DataTemplate. Either we create it in the Resource dictionary and set the binding as StaticResource in the actual control, or, we add the template directly inside the control. Both are similar ways. Let's go with the second approach to understand easily.

We need to add the ItemTemplate of the ListBox first before adding the DataTemplate. Inside DataTemplate, we create the template which we want to display and we do proper data binding before displaying any content.

Here is the older way to implement it:

image

Note that, here we will see the same output if we run the application. Because, we have a single DataTemplate to display them. We can't add multiple DataTemplates to the control based on the Data Type. Ohh!!! Alternative approach is creating two or more DataTemplates and load them dynamically from the code behind based on the data type. But that will not resolve our problem too. Using this approach, you can't mix the items of various data types in a single control. You need to handle it from the code behind as a workaround which is very tricky.

So, how to handle this in a simple and effective way? Microsoft recently launched the Silverlight 5 Beta which has a feature called ImplicitDataTemplates. Our article title is also on the same topic. Using this, you can easily do it in a proper way. How to do it? Let's start using the feature now and understand it very clearly.

Creating Implicit Data Types

Using Implicit Data Types, you can use multiple data templates for a single control instance and display the data accordingly in a proper fashion. We will use the same DataTemplate that we used in the previous example.

Remove the existing DataTemplate if you already added it inside the ListBox. Now, in the resource dictionary, copy the same template two times and change the display text accordingly. In our first template, we will set it as Employee and in the second template we will set it as Customer.

As per the new feature guideline, you need to specify the DataType of the DataTemplate. For the first template, add the DataType property as Employee and for the second use Customer as the DataType property.

Have a look into the below code snippet for understanding it very easily:

image

Download the complete XAML code here: MainView.xaml.

Demo

Now it's time to see it in action and understand the actual behaviour. Let's build and run the application. You will notice that it uses proper DataTemplate for proper Data Type. Check with the collection that we received from the DataService and match with the data in the UI. You will find them similar.

image

From this, we can understand that it loads the proper DataTemplate from the resource based on the data type. No need to bind the template to the control directly. Just place it in the resource dictionary and it will pick it directly from there based on the data type.

Download

The complete source code is available as a downloadable ZIP file. Download it from here: Silverlight 5 Beta, Implicit Data Template Source Code. Remember that the source code is based on the Silverlight 5 Beta version. It may or may not work in the future releases of Silverlight 5.

What Next?

Last but not least, I always welcome your feedback about my article. Please add a few comments at the end of the article and support me in delivering better content to you. Thank you for reading my articles and visiting my blog. I also tweet. Follow me on Twitter @kunal2383.

History

  • 08th May 2011, Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

_ Kunal Chowdhury _
Technical Lead
India India
Kunal Chowdhury is a Microsoft "Client Development" MVP (Most Valuable Professional), a Codeproject Mentor, Telerik MVP, Nokia Developer Champion, Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession.
 
He is currently working in an MNC located in India. He has a very good skill over XAML, C#, Silverlight, Windows Phone, WPF and Windows 8 (WinRT). He posts his findings, articles in his technical blog and CodeProject.
 
Technical Blog: http://www.kunal-chowdhury.com
Facebook: http://facebook.com/blog.kunal
Twitter : http://twitter.com/kunal2383
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinmvpBrij8-May-11 4:29 
GeneralRe: My vote of 5 PinmvpKunal_Chowdhury31-Jul-11 7:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 8 May 2011
Article Copyright 2011 by _ Kunal Chowdhury _
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid