WPF and making stuff pretty

I can thank my upbringing for demanding stuff looks good before anyone even sees it.  Appearance matters so how can one person make their application look good and have those styles and features be reusable?  First is to use Styles.  Styles much like CSS but are different.  With CSS in web pages, you can apply multiple styles to one element.  An example of this is

<div class="foo bar awesomer" style="width: 1.2em">Clint is awesomer</div>

With XAML, you can’t chain styles together but what you can do is create a hierarchy of styles.  Let me show you what I’m talking about in an example I used in my drunktender project.  This is a real world, working example.

<Style x:Key="leftSideStyleBase" TargetType="TextBlock">
	<Setter Property="FontWeight" Value="SemiBold" />
	<Setter Property="VerticalAlignment" Value="Center" />
	<Setter Property="Grid.Column" Value="0" />
	<Setter Property="TextWrapping" Value="Wrap" />
</Style>
<Style x:Key="pouringStyle" TargetType="TextBlock" BasedOn="{StaticResource leftSideStyleBase}">
	<Setter Property="FontSize" Value="35" />
	<Setter Property="Foreground" Value="#fff" />
</Style>
<Style x:Key="nonSelectedStyle" TargetType="TextBlock" BasedOn="{StaticResource leftSideStyleBase}">
	<Setter Property="FontSize" Value="25" />
	<Setter Property="FontWeight" Value="Bold" />
	<Setter Property="Margin" Value="10,0,0,0" />
	<Setter Property="Effect">
		<Setter.Value>
			<BlurEffect Radius="5" />
		</Setter.Value>
	</Setter>
</Style>
<Style x:Key="pouredStyle" TargetType="TextBlock" BasedOn="{StaticResource nonSelectedStyle}">
	<Setter Property="Foreground" Value="#B0ADFF" />
</Style>
<Style x:Key="notPouredStyle" TargetType="TextBlock" BasedOn="{StaticResource nonSelectedStyle}">
	<Setter Property="Foreground" Value="#969696" />
</Style>

You may not think that is amazing but I applied and set an effect through a style sheet!  I added an object to my XAML through just a Style sheet!

We’ve defined the styles, adding them is just as easy.

<TextBlock x:Name="pouring" Style="{DynamicResource pouringPulseStyle}">Pouring</TextBlock>

But Clint, what if we want to dynamically change them at run-time in code behind?  You can do something like this:

// style is in App.Xaml, ala Global Resource
myControl.Style = Application.Current.Resources["myStyle"] as Style;

// style is in a control, ala Local Resource
myControl.Style = Resources["myStyle"] as Style;

willem Jul 30, 2009 @ 2:42 AM

# re: WPF and making stuff pretty
Thanks Clint. Nice tip! I was not aware of the BasedOn attribute that you can use on a style. Learning as I go along... :)

Post a Comment

Please add 2 and 3 and type the answer here: