How Styles and ControlTemplates Work: The Control Contract

Monday, 26 May 2008 22:25 by snyhol

TECHNOLOGY USED: SILVERLIGHT 2, BETA 1

I recently posted some simple examples that demonstrate the power of Styles and ControlTemplates to skin your Silverlight applications.  Now let's talk about how it works.  Controls can be built to separate their visual appearance (i.e., the rectangular shape) from their behavior (i.e., firing a Click event).  This separation is facilitated with a "control contract" that implements the "parts control model."  This approach separates the appearance of the control into TemplateParts that can be replaced via ControlTemplates.  The contract specifies the following three items:

  • Public properties that can be set using Styles or inline property assignments
    • Defined as public DependencyProperty
  • UIElement objects that define the appearance
    • Defined with TemplatePart attributes
  • Storyboard objects that define how the control changes appearance in response to events
    • Defined with TemplatePart attributes

The Styling and Templating Overview provides this simple example of a control contract:

        [TemplatePart(Name = "RootElement", Type = typeof(FrameworkElement))]
        [
TemplatePart(Name = "FocusVisualElement", Type = typeof(FrameworkElement))]

        [
TemplatePart(Name = "Normal State", Type = typeof(Storyboard))]
        [
TemplatePart(Name = "MouseOver State", Type = typeof(Storyboard))]
        [
TemplatePart(Name = "Pressed State", Type = typeof(Storyboard))]

       
public class MyButton : Control {
           
public static readonly DependencyProperty TextProperty;
           
public static readonly DependencyProperty ForegroundProperty;
           
public static readonly DependencyProperty FontSizeProperty;

           
public string Text { get; set; }
           
public Brush Foreground { get; set; }
           
public double FontSize { get; set; }

        }

Learning about the control contract, or parts control model, will provide you with a deeper understanding of Styles and ControlTemplates.  New controls should be written with a control contract to allow others to skin them. 

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:  
Categories:   Software Dev
Actions:   E-mail | Permalink | Trackback | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

September 5. 2008 13:54