Posted by: Zeeshan Amjad | October 6, 2009

Using Data Template in List Box using C# Code


We have seen lots of example of using Data template in XAML, but hardly found any complete example in C#. Here we are going to study how can we apply the data template in List Box using C# code. It is important to note that creating template programmatically is not recommend by MSDN. It is recommended that we create template using XAML and load that XAML programmatically.

Let’s recall template little bit. Data template class is inherited by FrameworkTemplate class. Here is a class diagram of template classes.

Template_02

If we want to apply data template on list box then it is a multi step process. First we have to create our class with some properties, which we are going to use for data binding. Here is our simple class to store information about state and its capital.

  1: public class StateInfo
  2: {
  3:     public StateInfo(String state, String capital)
  4:     {
  5:         State = state;
  6:         Capital = capital;
  7:     }
  8: 
  9:     public String State
 10:     { get; set; }
 11: 
 12:     public String Capital
 13:     { get; set; }
 14: }
 15: 

In next step we are going to create a binding object and set the binding with the properties of this class. Here is a code to show this.

  1: Binding bindingState = new Binding();
  2: bindingState.Path = new PropertyPath("State");
  3: 
  4: Binding bindingCapital = new Binding();
  5: bindingCapital.Path = new PropertyPath("Capital");
  6: 

Till now there is nothing specific to data template. Now FrameworkElementFactory class joins the party. This class is used to create type programmatically which we are going to use in our data template.

  1: FrameworkElementFactory textState = new FrameworkElementFactory(typeof(TextBlock));

If we want to set some specific properties of newly created element then we have to call SetValue function explicitly and set the value of the property. Remember this property should be dependency property not normal CLR property.

  1: textState.SetBinding(TextBlock.TextProperty, bindingState);
  2: textState.SetValue(ForegroundProperty, Brushes.Blue);
  3: textState.SetValue(FontWeightProperty, FontWeights.Bold);
  4: 

We create the whole visual tree by using AppendChild method and set this to the visual tree property of data template.

  1: DataTemplate dt = new DataTemplate();
  2: 
  3: FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
  4: border.SetValue(BackgroundProperty, Brushes.LightYellow);
  5: border.SetValue(BorderBrushProperty, Brushes.Brown);
  6: border.SetValue(BorderThicknessProperty, new Thickness(3));
  7: border.SetValue(MarginProperty, new Thickness(5));
  8: 
  9: dt.VisualTree = border;
 10: 
 11: 

Here is the complete C# code to implement Data Template programmatically.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Windows;
  4: using System.Windows.Controls;
  5: using System.Windows.Media;
  6: using System.Windows.Data;
  7: 
  8: namespace MyListBox
  9: {
 10:     public class MyWindow : Window
 11:     {
 12:         public MyWindow()
 13:         {
 14:             Title = "List Box";
 15:             Width = 400;
 16:             Height = 300;
 17:             Background = Brushes.LightBlue;
 18: 
 19:             ListBox listBox = new ListBox();
 20:             listBox.Margin = new Thickness(10);
 21:             listBox.HorizontalContentAlignment = HorizontalAlignment.Stretch;
 22: 
 23:             DataTemplate dt = new DataTemplate();
 24: 
 25:             Binding bindingState = new Binding();
 26:             bindingState.Path = new PropertyPath("State");
 27: 
 28:             FrameworkElementFactory textState = new FrameworkElementFactory(typeof(TextBlock));
 29:             textState.SetBinding(TextBlock.TextProperty, bindingState);
 30:             textState.SetValue(ForegroundProperty, Brushes.Blue);
 31:             textState.SetValue(FontWeightProperty, FontWeights.Bold);
 32: 
 33:             Binding bindingCapital = new Binding();
 34:             bindingCapital.Path = new PropertyPath("Capital");
 35: 
 36:             FrameworkElementFactory textCapital = new FrameworkElementFactory(typeof(TextBlock));
 37:             textCapital.SetBinding(TextBlock.TextProperty, bindingCapital);
 38:             textCapital.SetValue(ForegroundProperty, Brushes.Black);
 39: 
 40:             FrameworkElementFactory stack = new FrameworkElementFactory(typeof(StackPanel));
 41:             stack.SetValue(MarginProperty, new Thickness(5));
 42:             stack.AppendChild(textState);
 43:             stack.AppendChild(textCapital);
 44: 
 45:             FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
 46:             border.SetValue(BackgroundProperty, Brushes.LightYellow);
 47:             border.SetValue(BorderBrushProperty, Brushes.Brown);
 48:             border.SetValue(BorderThicknessProperty, new Thickness(3));
 49:             border.SetValue(MarginProperty, new Thickness(5));
 50:             border.AppendChild(stack);
 51: 
 52:             dt.VisualTree = border;
 53: 
 54:             listBox.ItemTemplate = dt;
 55: 
 56:             List<StateInfo> listType = new List<StateInfo>();
 57: 
 58:             listType.Add(new StateInfo("Maryland", "Annapolis"));
 59:             listType.Add(new StateInfo("California", "Sacramento"));
 60:             listType.Add(new StateInfo("Massachusetts", "Boston"));
 61:             listType.Add(new StateInfo("Texas", "Austin"));
 62: 
 63:             listBox.ItemsSource = listType;
 64: 
 65:             Content = listBox;
 66:         }
 67:     }
 68: 
 69:     public class MyApplication
 70:     {
 71:         [STAThread]
 72:         public static void Main()
 73:         {
 74:             MyWindow win = new MyWindow();
 75:             Application app = new Application();
 76:             app.Run(win);
 77:         }
 78:     }
 79: 
 80:     public class StateInfo
 81:     {
 82:         public StateInfo(String state, String capital)
 83:         {
 84:             State = state;
 85:             Capital = capital;
 86:         }
 87: 
 88:         public String State
 89:         { get; set; }
 90: 
 91:         public String Capital
 92:         { get; set; }
 93:     }
 94: }
 95: 

Here is the output of this program.

ListBox_DataTemplate

Advertisements

Responses

  1. […] already saw an example of defining data template with code here. This time we are going to do the same thing, but with control template. We are going to define the […]

  2. Great, thank you 🙂

    • Thanks to like it.

  3. Thank you very much.
    Sayama Saitama Japan Takitaro2011


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: