This blog is where I post about my consulting work with Microsoft Technologies, and other random tidbits that don't fit in my Photo Blog or my Iraq Blog.

Friday, February 6, 2009

Applying (and blocking) global styles in WPF/Silverlight

I've been digging the ability to globally set default styles in a WPF/Silverlight application. For example I have a file named GlobalStyles.xaml that contains the default styles for all windows in my app:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"


    <!--Default styles that will apply to any object of the specified type (if it doesn't have style set locally)-->

    <Style TargetType="Button">

        <Setter Property="FontSize" Value="11"/>

        <Setter Property="FontWeight" Value="UltraBold"/>

        <Setter Property="Button.Margin" Value="10,0,10,0" />

        <Setter Property="Button.Padding" Value="3"  />

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

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


    <Style TargetType="Label" >

        <Setter Property="Margin" Value="10,0,10,0" />

        <Setter Property="FontSize" Value="11"/>

        <Setter Property="HorizontalAlignment" Value="Left"/>

        <Setter Property="VerticalAlignment" Value="Top"/>

        <Setter Property="MinWidth" Value="75"/>


This is all great EXCEPT when you DON'T want your groovy new global styles to apply to a window or specific element on your page. In my specific case the global style for "Button" was totally hosing the display of the WPFToolkit DataGrid which is itself composed of lots of WPF Buttons.

The answer is to put an EMPTY Style into the Resources section of the page or control that you want to block the global style from applying to. Here is the DataGrid specific example:


    <!--The following line overrides (blocks) the global default styles

    for "Button" from effecting the datagrid -->

    <Style TargetType="Button" />


You can do the same thing for the whole Window like this:


        <Style TargetType="Button" />


No comments: