Wednesday, September 12, 2012

Silverlight - TreeView DataBinding in Silverlight

In this article i will show you how to binding dynamic data to treeview control in Silverlight 4 application.

In Silverlight 4 you can directly access control from the toolbox.This is because the control is now a part of the Silverlight SDK. This is a great help to developers because they can easily create silverlight application which make use of the TreeView.

Let see how to use treeview control in silverlight 4 Application.

Step 1
Create a Database name TestDB with two tables such as MovieType and Movie, representing categories of movie and List of Movies.


USE TestDB;

CREATE TABLE MovieType
(
 TypeID NUMERIC(18,0) IDENTITY(1,1) PRIMARY KEY,
 [Type] Varchar(50)
)

CREATE TABLE Movie
(
 MovieID NUMERIC(18,0) IDENTITY(1,1) PRIMARY KEY,
 Title Nvarchar(50),
 MovieYear bigint,
 TypeID NUMERIC(18,0) FOREIGN KEY REFERENCES MovieType(TypeID)
)

1.Movie Type Table Data



Click on image for better view

2. Movie Table Data



Click on image for better view



Step 2
Create a Silverlight Application and give the solution name as SolDataBindingTreeView_Silverlight.



Click on image for better view

Note:Select Web Project Type as ASP.NET Web site and Select Silverlight 4 version.

Step 3
Select ASP.net Web project(SolDataBindingTreeView_Silverlight.Web) and right click on web project,select Add ASP.Net Folder and add App_Code folder in Solution.
In App_Code folder Create a another folder Name EF.

Step 4
Select EF folder and Right click on EF folder,Select Add New Item from Context menu,select ADO.NET Entity Data Model from Templates and rename the file, Model1.edmx, as MovieModel.edmx, Click on Add button.it's look like this.



Click on image for better view

Generate Model from Database,it is look like this



Click on image for better view

Connect Database to the Application,it is look like this.



Click on image for better view

Select TestDb Database and Save Entity Connection String in Web.Config File.

Select Database Objects.it is look like this



Click on image for better view

Select Both Tables click on Finish button.

Now Entities Created based on tables,it is look like this


  
Click on image for better view

Step 5
Select a ASP.net Web application(SolDataBindingTreeView_Silverlight.Web) and Add a WCF Service,right click on solution,select Add New Item,select WCF Service from installed Visual Studio templates and name it MovieService.svc and click on add button.

it will add two CS file in App_Code Folder I.E.(IMovieService.cs,MovieService.cs)



Click on image for better view

Step 6
Now we will make some modification to the OperationContract.Remove default DoWork method from the IMovieService interface.Add a new Method named as GetMovieData,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Collections;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMovieService" in both code and config file together.
[ServiceContract]
public interface IMovieService
{
    [OperationContract]
    List<EF.MovieType> GetMovieData();
    
}

Step 7
Implement IMovieService interface in Movieservice class and get movie data from databse,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MovieService" in code, svc and config file together.
public class MovieService : IMovieService
{

    /// <summary>
    /// Get Movie Data
    /// </summary>
    /// <returns>List</returns>
    public List<EF.MovieType> GetMovieData()
    {
        try
        {
            EF.TestDBEntities TEobj = new EF.TestDBEntities();

            return TEobj.MovieTypes.Include("Movies").ToList();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }
}

Step 8
Add a reference of  WCF Service in silverlight application(SolDataBindingTreeView_Silverlight).Right click the Silverlight project and add a Service reference,it is look like this




Click on image for better view

Step 9
Add a WCF service in the silverlight application.Add Service Reference dialog box will open and click on Discover button and give the namesapace name as MovieServiceReference,it's look like this



.Click on image for better view

Step 10
Add TreeView Control in UserControl.it is look like this
<Grid x:Name="LayoutRoot" Background="White">
        <sdk:TreeView x:Name="TvMovie" Grid.Row="0" Grid.Column="0">
         
        </sdk:TreeView>
    </Grid>

Step 11
Create a Templates for Nodes,For displaying data in nodes first we have to create a DataTemplate for display List of Movies later we have to create HierarchicalDataTemplate for display Types of Movie and then we can add it to this template and bind accordingly,it is look like this
<UserControl.Resources>
        
        <DataTemplate x:Key="MovieTemplate">
            <Border BorderThickness="2" CornerRadius="2" Background="Gray" Width="310">

                <Grid Width="300" Height="20">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.771*"/>
                        <ColumnDefinition Width="0.229*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="0.5*"/>
                    </Grid.RowDefinitions>

                    <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Title}"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding MovieYear}"></TextBlock>

                </Grid>
            </Border>
        </DataTemplate>

        <sdk:HierarchicalDataTemplate x:Key="MovieTypeTemplate" ItemsSource="{Binding Movies}" ItemTemplate="{StaticResource MovieTemplate}">
            <Border BorderThickness="2" CornerRadius="5" Background="Orange" Width="340">
                <TextBlock  Text="{Binding Type}" Margin="10,0,0,0" />
            </Border>
        </sdk:HierarchicalDataTemplate>
        
    </UserControl.Resources>

Step 12
Apply ItemTemplate on treeview control,it is look like this
<Grid x:Name="LayoutRoot" Background="White">
        <sdk:TreeView x:Name="TvMovie" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}" ItemTemplate="{StaticResource MovieTypeTemplate}">
         
        </sdk:TreeView>
    </Grid>

Step 13
In MainPage.xaml.cs, add code as shown below. The code creates an instance of the service class, invokes the service method asynchronously and reads the return value from the service method and bind values to DataContext property of the TreeView Control.,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SolDataBindingTreeView_Silverlight
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            try
            {
                BindTreeView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
        }

        #region Methods

        /// <summary>
        /// Call WCF Service to binding Movie Data to TreeView Control.
        /// </summary>
        public void BindTreeView()
        {
            try
            {
                // Call WCF Service 
                MovieServiceReference.MovieServiceClient MSCObj = new MovieServiceReference.MovieServiceClient();

                // Wire up the Async Completed  handler
                MSCObj.GetMovieDataCompleted += new EventHandler<MovieServiceReference.GetMovieDataCompletedEventArgs>(MSCObj_GetMovieDataCompleted);

                // Call WCF Method  
                MSCObj.GetMovieDataAsync();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }

        void MSCObj_GetMovieDataCompleted(object sender, MovieServiceReference.GetMovieDataCompletedEventArgs e)
        {
            try
            {
                if (e != null)
                {
                    // Bind the Movie Data in TreeView 
                    TvMovie.DataContext = e.Result;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion
    }
}


Run the project.

Output



.Click on image for better view


.Click on image for better view

Full XAML CODE
<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" 
 x:Class="SolDataBindingTreeView_Silverlight.MainPage"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <UserControl.Resources>
        
        <DataTemplate x:Key="MovieTemplate">
            <Border BorderThickness="2" CornerRadius="2" Background="Gray" Width="310">

                <Grid Width="300" Height="20">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.771*"/>
                        <ColumnDefinition Width="0.229*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="0.5*"/>
                    </Grid.RowDefinitions>

                    <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Title}"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding MovieYear}"></TextBlock>

                </Grid>
            </Border>
        </DataTemplate>

        <sdk:HierarchicalDataTemplate x:Key="MovieTypeTemplate" ItemsSource="{Binding Movies}" ItemTemplate="{StaticResource MovieTemplate}">
            <Border BorderThickness="2" CornerRadius="5" Background="Orange" Width="340">
                <TextBlock  Text="{Binding Type}" Margin="10,0,0,0" />
            </Border>
        </sdk:HierarchicalDataTemplate>
        
    </UserControl.Resources>
    
    <Grid x:Name="LayoutRoot" Background="White">
        <sdk:TreeView x:Name="TvMovie" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}" ItemTemplate="{StaticResource MovieTypeTemplate}">
         
        </sdk:TreeView>
    </Grid>
</UserControl>


Download
Download Source Code

3 comments:

  1. Nice Code.....Kishor

    ReplyDelete
  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete