Sunday, September 23, 2012

Image Gallery in Window Phone 7

In this article i will show you how to create dynamic Simple Image Gallery in Window Phone 7 by using WrapPanel Control to layout Album thumbnails to the screen.

Step 1
To Develop application for Windows Phone 7 devices, you need to install Windows Phone 7.1 SDK and toolkit. You can download latest SDK for Windows Phone
http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=27570

SDK 7.1.1 Update
https://dev.windowsphone.com/en-us/downloadsdk

Silverlight for Window Phone Toolkit
http://silverlight.codeplex.com/releases/view/75888


Install SDK and Toolkit on your Machine.

Step 2
Create a Window Phone Application and give the solution name as SolImageGallery_WP7.
To start creating a new Windows Phone application, start Microsoft Visual Studio then create a new Project and select Windows Phone Application Template,it is look like this



Click on Image for better View

Step 3
Select the Window Phone Platform,it is look like this



Click on Image for better View

Step 4
Adding Silverlight Window Phone Toolkit Reference.
To add a reference, right click the References folder of your project in Solution Explorer and select Add Reference.On this dialog, Select Extensions in Assemblies,Select Microsoft.Phone.Controls.Toolkit,Click on Add Button,it is look like this



Click on Image for better View

Microsoft.Phone.Controls.Toolkit Path
C:\Program Files\Microsoft SDKs\Windows Phone\v7.1\Toolkit\Oct11\Bin\Microsoft.Phone.Controls.Toolkit.dll

Step 5
Add a System.Xml.Linq Assemble reference to the project.Right click on the project name in Solution Explorer, select Add Reference and Select System.Xml.Linq  and select OK button,it is look like this



Click on Image for better View

Step 6
Save images in Folder,Create a New Folder in the Solution and give folder name as Images,it is look like this




Click on Image for better View

Step 7
Add XML file in the solution and give the file name as ImageData.xml,it is look like this



Click on Image for better View

Step 8
The XML in the following example defines an XML document with a root node called Images. This root node contains one or more nodes called Image that include elements called ImageName and ImagePath.
<?xml version="1.0" encoding="utf-8" ?>
<Images>

<Image>
  <ImageName>Gaara</ImageName>
  <ImagePath>../Images/Gaara.png</ImagePath>
  </Image>

  <Image>
    <ImageName>Choji</ImageName>
    <ImagePath>../Images/Choji.png</ImagePath>
  </Image>

  <Image>
    <ImageName>Jiraiya</ImageName>
    <ImagePath>../Images/Jiraiya.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Kakashi</ImageName>
    <ImagePath>../Images/Kakashi.png</ImagePath>
  </Image>

<Image>
    <ImageName>Kiba</ImageName>
    <ImagePath>../Images/Kiba.png</ImagePath>
  </Image>
<Image>
  <ImageName>Naruto</ImageName>
    <ImagePath>../Images/Naruto.jpg</ImagePath>
  </Image>

<Image>
    <ImageName>Neji</ImageName>
    <ImagePath>../Images/Neji.jpg</ImagePath>
  </Image>

<Image>
    <ImageName>RockLee</ImageName>
    <ImagePath>../Images/RockLee.jpg</ImagePath>
  </Image>

<Image>
    <ImageName>Sai</ImageName>
    <ImagePath>../Images/Sai.jpg</ImagePath>
  </Image>

<Image>
    <ImageName>Shikamaru</ImageName>
    <ImagePath>../Images/Shikamaru.jpg</ImagePath>
  </Image>

<Image>
    <ImageName>Shino</ImageName>
    <ImagePath>../Images/Shino.jpg</ImagePath>
  </Image>

<Image>
    <ImageName>Yamato</ImageName>
    <ImagePath>../Images/Yamato.jpg</ImagePath>
  </Image>

</Images>


Step 9
Create an ImageEntity Class in the solution,it is look like this
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SolImageGallery_WP7
{
    public class ImageEntity
    {
        #region proeprty

        /// <summary>
        /// Get And Set Image Name
        /// </summary>
        public String ImageName
        {
            get;
            set;
        }

        /// <summary>
        /// Get And Set Image Path
        /// </summary>
        public String ImagePath
        {
            get;
            set;
        }

        #endregion
    }
}

Step 10
Create a ImageView static class in a solution for retrieving data from XML document.it is look like this
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace SolImageGallery_WP7
{
    public static class ImageView
    {
       /// <summary>
        ///  Retrieve Data from XML Document
       /// </summary>
       /// <returns>List</returns>
       public static List<ImageEntity> GetDataFromXML()
        {
            try
            {
                // Load XML Document
                XDocument XDoc = XDocument.Load("ImageData.xml");

                //Query for retrieving all Images data from XML
                var Query = from Q in XDoc.Descendants("Image")
                            select new ImageEntity
                            {
                                ImageName=Q.Element("ImageName").Value,
                                ImagePath=Q.Element("ImagePath").Value
                            };

                // Reutn Data
                return Query.ToList<ImageEntity>();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }
    }
}

Step 11
Now design Image gallery on page.Drag and drop ListBox Control from Toolbox.it is look like this
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
         <ListBox x:Name="LstImageGallery" />      
</Grid>

Step 12
Add toolkit reference in XAML,so we can Add WrapPanel Control in Phone Application Page,it is look like this
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

Finally it's look like this
<phone:PhoneApplicationPage
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" 
    xmlns:ec="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions" 
    x:Class="SolImageGallery_WP7.MainPage"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">


Step 13
Create a ItemPanelTemplate for ListBox Control in phone:PhoneApplicationPage.Resources to Display Images in WrapPanel Control,it is look like this
<ItemsPanelTemplate x:Key="ListItemsPanelTemplate">
   <toolkit:WrapPanel ItemWidth="150" ItemHeight="150" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</ItemsPanelTemplate>

Step 14
Create a DataTemplate for ListBox Control in phone:PhoneApplicationPage.Resources to bind Image Path and Image Name in Image and TextBlock Control,it is look like this
<DataTemplate x:Key="ListDataTemplate">
   <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
    
    <Border BorderBrush="#FFFF9800" BorderThickness="3"  Width="120" Height="120"  CornerRadius="10">
     <Image x:Name="image" Source="{Binding ImagePath}" Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="Fill"/>
    </Border>
    
    <TextBlock Text="{Binding ImageName}" Style="{StaticResource PhoneTextSubtleStyle}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    
   </StackPanel>
</DataTemplate>


Finally DataTemplate and ItemPanelTemplate look like this
<phone:PhoneApplicationPage.Resources>
  
  <ItemsPanelTemplate x:Key="ListItemsPanelTemplate">
   <toolkit:WrapPanel ItemWidth="150" ItemHeight="150" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  </ItemsPanelTemplate>
  
  <DataTemplate x:Key="ListDataTemplate">
   <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
    
    <Border BorderBrush="#FFFF9800" BorderThickness="3"  Width="120" Height="120"  CornerRadius="10">
     <Image x:Name="image" Source="{Binding ImagePath}" Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="Fill"/>
    </Border>
    
    <TextBlock Text="{Binding ImageName}" Style="{StaticResource PhoneTextSubtleStyle}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    
   </StackPanel>
  </DataTemplate>
</phone:PhoneApplicationPage.Resources>

Step 15
Apply DataTemplate and ItemPanelTemplate on ListBox Control,it is look like this
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
         <ListBox x:Name="LstImageGallery" ItemsSource="{Binding}" ItemsPanel="{StaticResource ListItemsPanelTemplate}" ItemTemplate="{StaticResource ListDataTemplate}"/>      
</Grid>


ItemSource Property - Gets or sets a collection used to generate the content of the ItemsControl.

ItemTemplate Property - Gets or sets the DataTemplate used to display each item.

ItemPanel Property -  Gets or sets the template that defines the panel that controls the layout of items.


Step 16
Now Bind the data in ListBox Control in Code Behind,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;
using Microsoft.Phone.Controls;


namespace SolImageGallery_WP7
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                BindImages(); // Call Bind Images Function in Application Page Load Event
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
        }

        #region Methods
        /// <summary>
        /// Bind Image in List Box Control
        /// </summary>
        public void BindImages()
        {
            try
            {
                // Store Data in List Object
                List<ImageEntity> ListImages = ImageView.GetDataFromXML();

                // Check List Object is Null or Not
                if (ListImages != null)
                {
                    // Check List Object Count
                    if (ListImages.Count > 0)
                    {
                        // Bind Data in List Box Control.
                        LstImageGallery.DataContext = ListImages;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }

        #endregion
    }
}

Run the project.

Output



Click on Image for better View

Full XAML Code
<phone:PhoneApplicationPage
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" 
    xmlns:ec="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions" 
    x:Class="SolImageGallery_WP7.MainPage"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">
    
 <phone:PhoneApplicationPage.Resources>
  
  <ItemsPanelTemplate x:Key="ListItemsPanelTemplate">
   <toolkit:WrapPanel ItemWidth="150" ItemHeight="150" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  </ItemsPanelTemplate>
  
  <DataTemplate x:Key="ListDataTemplate">
   <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
    
    <Border BorderBrush="#FFFF9800" BorderThickness="3"  Width="120" Height="120"  CornerRadius="10">
     <Image x:Name="image" Source="{Binding ImagePath}" Width="100" Height="100" HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="Fill"/>
    </Border>
    
    <TextBlock Text="{Binding ImageName}" Style="{StaticResource PhoneTextSubtleStyle}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    
   </StackPanel>
  </DataTemplate>
 </phone:PhoneApplicationPage.Resources>
 
    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->
 
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Image Gallery" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
         <ListBox x:Name="LstImageGallery" ItemsSource="{Binding}" ItemsPanel="{StaticResource ListItemsPanelTemplate}" ItemTemplate="{StaticResource ListDataTemplate}"/>      
  </Grid>
    </Grid>

</phone:PhoneApplicationPage>


Download
Download Source Code

I had created a another Image gallery using LongListSelector in Window Phone 8.
http://kishor-naik-dotnet.blogspot.in/2013/11/wp8-longlistselector-in-window-phone-8.html


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