WPFAQS – Templates in WPF/XAML

WPFAQS – is a series on WPF frequently asked questions (FAQS). Today we will discuss about different templates, like “ControlTemplate”, “DataTemplate”, “HierarchicalDataTemplate” and “ItemsPanelTemplate”, in WPF and their usage.

WPFAQS(003) – What are the different types of Templates in WPF/XAML, explain with examples

In the last WPFAQ, I discussed the logical and visual trees. In this post I will expand my discussion on different types of templates and how they are related to visual trees. All the templates In WPF all derived from the abstract FrameworkTemplate class. ControlTemplate is a visual tree of a UI controls such as a Button or ListView/GridView control while DataTemplate is used to visualize the model/business object in terms of UI components defined in the DataTemplate or the business objects render themselves to the visual tree defined in the DataTemplate. For its example please refer to my [Posting] where enums are rendered to some combobox items or so. HierarchicalDataTemplate is also a DataTemplate but, as the name suggests, is suitable for hierarchal/recursive data structures like Trees or the model based on composite design pattern. ItemsControl and its derived classes like Comboboxes and ListBoxes create Layout panels called ItemsPanelTemplate for controlling the layout of their respective children. You may consider overriding it in order to change the default behavior of their layout. Here is the class diagram that shows their relationships with each other :


And, here is an example XAML, that shows DataTemplates as well as ItemsPanelTemplate that I took it from an example application “LegoDraw” that I am planning to post in the near future:

   1:  <UserControl x:Class="Shams.Wpf.LegoDraw.Controls.LegoDrawBoard"
   2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:      xmlns:local="clr-namespace:Shams.Wpf.LegoDraw.Controls"
   5:      xmlns:model="clr-namespace:Shams.Wpf.LegoDraw.Model"         
   6:      HorizontalAlignment ="Stretch"
   7:      HorizontalContentAlignment ="Stretch"
   8:      VerticalAlignment ="Stretch"
   9:      VerticalContentAlignment ="Stretch"
  10:      local:LegoDrawBoard.TotalColors="9"
  11:      x:Name="This">
  13:      <UserControl.Resources>
  14:          <ResourceDictionary>
  15:              <DataTemplate DataType="{x:Type model:CellWidget}">
  16:                  <Grid Width="Auto" Height="Auto">
  17:                      <Border x:Name="PART_Border" 
  18:                              BorderThickness="4" 
  19:                              Background="{Binding Path=Background}"
  20:                              BorderBrush="{Binding Path=BorderBrush}" 
  22:                              MouseLeftButtonDown="PART_Border_MouseLeftButtonDown"
  23:                              MouseMove="PART_Border_MouseMove"
  24:                              MouseLeftButtonUp="PART_Border_MouseLeftButtonUp" />
  25:                  </Grid>
  26:                  <DataTemplate.Triggers>
  27:                      <DataTrigger Binding="{Binding Path=CellId}" Value="{x:Null}">
  28:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="Transparent" />
  29:                      </DataTrigger>
  30:                      <DataTrigger Binding="{Binding Path=CellId}" Value="0">
  31:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="Yellow" />
  32:                      </DataTrigger>
  33:                      <DataTrigger Binding="{Binding Path=CellId}" Value="1">
  34:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="Cyan" />
  35:                      </DataTrigger>
  36:                      <DataTrigger Binding="{Binding Path=CellId}" Value="2">
  37:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="Red" />
  38:                      </DataTrigger>
  39:                      <DataTrigger Binding="{Binding Path=CellId}" Value="3">
  40:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="Blue" />
  41:                      </DataTrigger>
  42:                      <DataTrigger Binding="{Binding Path=CellId}" Value="4">
  43:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="Purple" />
  44:                      </DataTrigger>
  45:                      <DataTrigger Binding="{Binding Path=CellId}" Value="5">
  46:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="SpringGreen" />
  47:                      </DataTrigger>
  48:                      <DataTrigger Binding="{Binding Path=CellId}" Value="6">
  49:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="Pink" />
  50:                      </DataTrigger>
  51:                      <DataTrigger Binding="{Binding Path=CellId}" Value="7">
  52:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="Orange" />
  53:                      </DataTrigger>
  54:                      <DataTrigger Binding="{Binding Path=CellId}" Value="8">
  55:                          <Setter TargetName="PART_Border" Property="BorderBrush" Value="SteelBlue" />
  56:                      </DataTrigger>
  57:                  </DataTemplate.Triggers>
  58:              </DataTemplate>
  60:              <DataTemplate x:Key ="GridRowTemplate">
  61:                  <ItemsControl ItemsSource ="{Binding Path=CellsRow}">
  62:                      <ItemsControl.ItemsPanel>
  63:                          <ItemsPanelTemplate>
  64:                              <UniformGrid Columns ="1"/>
  65:                          </ItemsPanelTemplate>
  66:                      </ItemsControl.ItemsPanel>
  67:                  </ItemsControl>
  68:              </DataTemplate>
  69:          </ResourceDictionary>
  70:      </UserControl.Resources>
  72:      <Grid x:Name="MainGrid" >
  73:          <Grid.DataContext>
  74:              <Binding ElementName="This" Path="MainGridWidget" />
  75:          </Grid.DataContext>
  76:          <Border BorderBrush="Silver" BorderThickness="2" >
  77:              <ItemsControl x:Name ="LegoDrawItemsControl" 
  78:                            ItemTemplate ="{StaticResource GridRowTemplate}" 
  79:                            ItemsSource ="{Binding Path=GridRows}" >
  80:                  <ItemsControl.ItemsPanel>
  81:                      <ItemsPanelTemplate>
  82:                          <UniformGrid Rows ="1"/>
  83:                      </ItemsPanelTemplate>
  84:                  </ItemsControl.ItemsPanel>
  85:              </ItemsControl>
  86:          </Border>
  87:      </Grid>
  88:  </UserControl>

If you look at lines 64 and 82  above, you will see that we override the default “ItemsPanelTemplate” with the “UniformGrid” panel. Also have a look at the DataTemplate part line-15, where the Binding is a business object “CellWidget” and will be rendered as Border UI at run time.

I hope you now have a clear understanding of the templates, if not then pass on me your question for more clarification on them. That's all for now and look forward to your feed-back. enjoy :)


If you enjoyed reading this blog, leave your valuable feedback and consider subscribing to the RSS feed. You can also subscribe to it by email. Also, you can follow me on Twitter. Thank you!

Comments (13) -

Cerebral Boost
3/19/2018 7:58:19 PM #

Hey there! This post couldn't be written any better! Reading through this post reminds me of my good old room mate! He always kept chatting about this. I will forward this write-up to him. Fairly certain he will have a good read. Thank you for sharing!

Cerebral Boost
3/19/2018 8:03:34 PM #

I like this post, enjoyed this one regards for posting.

Cerebral Boost Shark Tank
3/19/2018 8:14:57 PM #

Heya i am for the first time here. I found this board and I find It really useful & it helped me out a lot. I hope to give something back and help others like you aided me.

Claira Care Cream
3/19/2018 10:06:58 PM #

This website really has all the info I needed concerning this subject and didn?t know who to ask.

Claira Care Cream
3/19/2018 10:07:41 PM #

I consider something really interesting about your website so I saved to favorites.

Unlimited Fit Garcinia Reviews
3/19/2018 10:17:08 PM #

Rattling clear web site, thanks for this post.

ThermoBurn Review
3/19/2018 10:49:04 PM #

This piece of writing will assist the internet people for setting up new website or even a weblog from start to end.

ThermoBurn Reviews
3/19/2018 11:03:43 PM #

Hey there I am so happy I found your site, I really found you by mistake, while I was researching on Askjeeve for something else, Nonetheless I am here now and would just like to say thanks a lot for a fantastic post and a all round interesting blog (I also love the theme/design), I don?t have time to read it all at the moment but I have saved it and also added your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the superb work.

ThermoBurn Review
3/19/2018 11:04:05 PM #

It's really a cool and useful piece of information. I am glad that you shared this helpful info with us. Please keep us informed like this. Thank you for sharing.

Enduraflex Performance
3/19/2018 11:06:31 PM #

I would like to consider the opportunity of thanking you for that professional instruction I have often enjoyed checking out your site. We are looking forward to the actual commencement of my college research and the entire preparing would never have been complete without browsing your web site. If I might be of any assistance to others, I'd be happy to help by means of what I have gained from here.

Enduraflex Performance
3/19/2018 11:07:32 PM #

Thank you for the sensible critique. Me & my neighbor were just preparing to do a little research about this. We got a grab a book from our area library but I think I learned more clear from this post. I'm very glad to see such excellent info being shared freely out there.

Enduraflex Performance
3/20/2018 12:11:17 AM #

Wow! This could be one particular of the most beneficial blogs We have ever arrive across on this subject. Actually Magnificent. I am also a specialist in this topic therefore I can understand your effort.

Enduraflex Performance Plus
3/20/2018 12:13:41 AM #

Hey there would you mind letting me know which web host you're using? I've loaded your blog in 3 completely different internet browsers and I must say this blog loads a lot faster then most. Can you suggest a good internet hosting provider at a fair price? Thanks, I appreciate it!

Enduraflex Performance Plus
3/20/2018 12:15:01 AM #

I'll immediately grab your rss as I can not in finding your e-mail subscription link or e-newsletter service. Do you've any? Kindly permit me understand in order that I could subscribe. Thanks.

Optimum Garcinia
3/20/2018 1:21:02 AM #

I wanted to thank you for this great read!! I absolutely enjoyed every bit of it. I have you saved as a favorite to check out new things you post...

Optimum Garcinia Diet Side Effects
3/20/2018 1:22:18 AM #

Way cool! Some extremely valid points! I appreciate you writing this article and the rest of the website is extremely good.

Optimum Garcinia Diet Side Effects
3/20/2018 1:28:50 AM #

Simply want to say your article is as astonishing. The clearness in your post is just nice and i could assume you're an expert on this subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the gratifying work.

Thin Garcinia Review
3/20/2018 3:02:54 AM #

Your way of explaining everything in this article is actually fastidious, every one can easily understand it, Thanks a lot.

Pure Essence CBD Reviews
3/20/2018 3:29:33 AM #

I love the efforts you have put in this, thanks for all the great posts.

Pure Essence CBD Reviews
3/20/2018 3:33:13 AM #

I all the time used to study article in news papers but now as I am a user of web so from now I am using net for content, thanks to web.

Pure Essence CBD Oil
3/20/2018 3:34:41 AM #

I'm extremely impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you customize it yourself? Anyway keep up the excellent quality writing, it is rare to see a nice blog like this one nowadays.

Pure Essence CBD Review
3/20/2018 3:35:46 AM #

I like the efforts you have put in this, appreciate it for all the great articles.

Luxe Derme Anti Aging Cream
3/20/2018 4:09:35 AM #

Hey would you mind letting me know which web host you're working with? I've loaded your blog in 3 completely different browsers and I must say this blog loads a lot faster then most. Can you recommend a good internet hosting provider at a reasonable price? Thank you, I appreciate it!

Add comment