Derived Styles based on unnamed default Styles

This seems so obvious in retrospect but I just learned something very useful today so I thought I’d put it out there just in case anyone else wasn’t aware of this.

Specifically the problem occurs when you create a style in Xaml that is supposed to be the default style for a particular type of Control. For example:

<Style TargetType="{x:Type ComboBox}">
</Style>

This will allow you to create a style for all ComboBoxes. If a ComboBox does not specify a specific Style it will get this one automatically. The tricky part comes when you want a single particular ComboBox to deviate from the style just a little bit. So typically what I do is create the main Style that is named then create the default Style to be based on that main one like:

<Style x:Key="ComboBoxBase" TargetType="{x:Type ComboBox}">
</Style>
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource ComboBoxBase}">
</Style>

Then if you make any further custom styles they can just be based on ComboBoxBase and change as necessary. While this works I just found a way that is potentially cleaner. It turns out that you can pass in a Type to the StaticResource instead of a key and get at the default Style for that Type. Very handy, like so:

<Style TargetType="{x:Type ComboBox}">
</Style>
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
</Style>

How did I not know this sooner? This way you put all of your main styling into the official default Style, you also don’t need to remember the name of that default Style to use it.

Disclaimer: I haven’t tried this on Silverlight, only WPF.

Advertisements

Drop a brain bomb

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s