Alessandro Del Sole's Blog

/* A programming space about Microsoft® .NET® */
posts - 159, comments - 0, trackbacks - 0

My Links

News

Your host

This is me! This space is about Microsoft® .NET® and Microsoft® Visual Basic development. Enjoy! :-)

These postings are provided 'AS IS' for entertainment purposes only with absolutely no warranty expressed or implied and confer no rights.

Microsoft MVP

My MVP Profile

I'm a VB!

Watch my interview in Seattle

My new book on VB 2015!

Pre-order VB 2015 Unleashed Pre-order my new book "Visual Basic 2015 Unleashed". Click for more info!

My new book on LightSwitch!

Visual Studio LightSwitch Unleashed My book "Visual Studio LightSwitch Unleashed" is available. Click the cover!

Your visits

Follow me on Twitter!

CodePlex download Download my open-source projects from CodePlex!

Article Categories

Archives

Post Categories

.NET Framework

Blogroll

Help Authoring

Microsoft & MSDN

Setup & Deployment

Visual Basic 2005/2008/2010

Style inheritance in WPF

In Windows Presentation Foundation, styles support inheritance. In fact it's possible to declare a base style and styles which derive from the base. The main difference is that when defining a style you cannot specify the type of control the style is bound to. Or better, the type of object which can receive the style must be of type IFrameworkInputElement.

The following sample will allow you to understand. First of all, we declare a base stile with XAML, from within the resources:

    <Style x:Key="MyStyle">

      <Setter Property="Button.FontFamily" Value="Courier New"/>

      <Setter Property="Button.FontSize" Value="12" />

      <Setter Property="Button.Background" Value="Orange" />

      <Setter Property="Button.Width" Value="150" />

      <Setter Property="Button.Height" Value="75" />

    </Style>

This simple style defines font properties, background and size of button. Notice how (referring to what we said at the beginning) it's necessary to specify the control which the property belongs to, instead of using an only TargetType attribute. The second step is to declare the derived style: 

    <Style x:Key="MyInheritedStyle" BasedOn="{StaticResource MyStyle}">

      <Setter Property="Button.Foreground" Value="Blue" />

    </Style>

As you can see, the BasedOn attribute specifies the base style. Now we have all the base style properties plus the foreground color we added now.

This code draws a simple button:

      <Button Style="{StaticResource MyInheritedStyle}" Margin="10,10,10,10">

        Hello WPF!

      </Button>

You can just run the application to see a button with orange background and blue foreground colors. 

Alessandro

Print | posted on martedì 14 aprile 2009 14:22 | Filed Under [ Windows Presentation Foundation ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 7 and 8 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET