Gigi Labs

Sunday, September 8, 2013

C# WPF: Styling buttons in a window

Hi! :)

In this article we'll take a look at WPF styles, which allow us to manage the properties of many controls in one place. If you've used HTML and CSS in the past, this is a bit like how CSS allows you to customise the layout of HTML elements, leaving HTML to focus on the structure of the document.

To see how styling works, we'll create a Tic Tac Toe application (just the buttons... the logic is beyond the scope of the article). Start off by creating a new WPF application (I'm using Visual Studio 2012, but you may just as well use SharpDevelop or some other version of Visual Studio):

In MainWindow.xaml, you get some default XAML code. In VS2012, it looks like this:

A WPF UniformGrid gives us an easy way to make an nxn grid, and in Tic Tac Toe we want a 3x3 grid, so UniformGrid is perfect for the job. Change the XAML as follows (I've also edited some properties of the window):

<Window x:Class="CsWpfStyleButtons.MainWindow"

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

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Tic Tac Toe" Height="200" Width="200">

<UniformGrid>

<Button>X</Button>

<Button></Button>

<Button>O</Button>

<Button></Button>

<Button></Button>

<Button>X</Button>

<Button></Button>

<Button>O</Button>

<Button></Button>

</UniformGrid>

</Window>

At this point, we get this:

Right, so what if we want to customise it? We might want a bigger font, for instance, but that would require setting the same attributes on each and every button. If we add a few more properties, the XAML quickly becomes a nightmare to maintain:

To make our life much easier, we can use styles. We define styles in a Window.Resources section, that goes just after the <Window> declaration and before the <UniformGrid>:

<Window.Resources>

<Style TargetType="{x:Type Button}">

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

<Setter Property="Foreground" Value="DarkGreen" />

<Setter Property="Margin" Value="3" />

<Setter Property="FontFamily" Value="Verdana" />

<Setter Property="BorderBrush" Value="AliceBlue" />

</Style>

</Window.Resources>

Here we define a style that works on elements of type Button. We can remove all the attributes from our buttons and into setters in this style, as above. If you run the application, you'll see that it just works:

Styles are quite powerful, and allow us to separate structure and style to a certain extent, much in the way we use HTML to control the structure of a webpage and CSS to style it. Styles allow us to apply the same properties to all controls of a particular type, as we have done here. They also allow us to affect particular elements of our choice, by setting an x:Key attribute instead of a TargetType, much in the manner of CSS classes.