How to apply Template to Silverlight Control ? Get the RSS for this comments
When you want to create a new silverlight control that can have a template applied to it. The scenario happens when you want to create custom look and feel on the control. Template is just like CSS file but in XAML fromat.

1 Comment(s) | 1027 View(s) | 3 Vote(s) | Average rating: 4.3 Rated | Tutorials Category | dhiraj Submitted on 1/1/2009

When you want to create a new silverlight control that can have a template applied to it.  The scenario happens when you want to create custom look and feel on the control. Template is just like CSS file but in XAML fromat.

Let’s start with this control definition:

   1: using System;
   2: using System.Windows.Controls;
   3: using System.Windows.Markup;
   4:  
   5: namespace ControlTemplate
   6: {
   7:     [ContentProperty("Content")]
   8:     public class DemoTemplatedControl : ContentControl
   9:     {
  10:  
  11:     }
  12: }

Then you create your generic.xaml file under the themes folder, and you add a template for your control.

 

   1: <ResourceDictionary
   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:ControlTemplate">
   5:     
   6:     <Style TargetType="local:DemoTemplatedControl">
   7:         <Setter Property="Template">
   8:             <Setter.Value>
   9:                 <ControlTemplate TargetType="local:DemoTemplatedControl">
  10:                     <TextBlock Text="This is my custom control template" />
  11:                 </ControlTemplate>
  12:             </Setter.Value>
  13:         </Setter>
  14:     </Style>
  15: </ResourceDictionary>

Without setting the DefaultStyleKey property to the control’s own type, the template doesn’t get applied.  Set that property in your constructor.

   1: <UserControl x:Class="ControlTemplate.Page"
   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:ControlTemplate">
   5:     <Grid x:Name="LayoutRoot" Background="White">
   6:         <local:DemoTemplatedControl />
   7:     </Grid>
   8: </UserControl>


 You set  this.DefaultStyleKey propert .

   1: using System;
   2: using System.Windows.Controls;
   3: using System.Windows.Markup;
   4:  
   5: namespace ControlTemplate
   6: {
   7:     [ContentProperty("Content")]
   8:     public class DemoTemplatedControl : ContentControl
   9:     {
  10:         public DemoTemplatedControl()
  11:         {
  12:             this.DefaultStyleKey = typeof(DemoTemplatedControl);
  13:         }
  14:     }
  15: }

 


How would you rate this article?

User Comment(s)

Comment posted by satyarathore05 on Sunday, January 11, 2009 5:07 PM
see it

Name:
E-mail:
Url:
Comment:
Insert Cancel