Search content within the blog

Tuesday, July 26, 2011

Styles in WPF

The following sample shows how styles can be applied at page level in WPF. The style details are encapsulated under <Window.Resources> tags. Each style that you create must have a unique name associated with it. This is done by the key property.
Setting the Key property to unique names created unique style elements. The creation of style is very similar to the way it is done in web applications.

Once the style elements are created we need to associate the control with the style name.

Note: We specify the style as "Control.Property" example "TextBlock.Background" the reason being some of the controls do not understand when you just specify the property that you want to modify or style. Example a "TextBlock" does not understand when you just say "Background". You need to explicitly specify "Control.Property" for it to work properly.



XAML Code.

<Window x:Class="applystyles_cs.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="applystyles_cs" Height="300" Width="300"
>
<Window.Resources>

<Style x:Key="myTextstyle">
<Setter Property="TextBlock.Background" Value="Black" />
<Setter Property="TextBlock.Margin" Value="10,10,10,5" />
<Setter Property="TextBlock.Foreground" Value="White" />
<Setter Property="TextBlock.FontSize" Value="20" />
<Setter Property="TextBlock.HorizontalAlignment" Value="Center" />
</Style>

<Style x:Key="btnstyle">
<Setter Property="Button.Margin" Value="10,5,10,10" />
<Setter Property="Button.Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="Blue" />
<GradientStop Offset="1" Color="Red" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Button.HorizontalAlignment" Value="Center" />
</Style>

</Window.Resources>

<StackPanel>
<TextBlock Style="{StaticResource myTextstyle}">
Hello
</TextBlock>
<Button Style="{StaticResource btnstyle}">
Click Me</Button>
</StackPanel>
</Window>

No comments:

Post a Comment