Appendix M. Styles
A Style
lets you define a package of properties that you can later assign as a group to make controls more consistent and to make the code easier to read.
You can define Styles
in a control's Resources section. If you are going to share a Style
, it is most convenient to place it in a container's Resources section.
Typically a Style
contains Setter
and EventSetter
objects that define specific property values and event handlers for the controls that use the Style
.
You can make two kinds of Styles
: named and unnamed.
Named Styles
To make a named Style
, give it an x:Name
attribute. Later you can refer to the Style
as a StaticResource
.
The following XAML code defines and uses a Style
named styButton
:
<StackPanel Orientation="Horizontal"> <StackPanel.Resources> <Style x:Key="styButton" TargetType="Button"> <Setter Property="Width" Value="100"/> <Setter Property="Height" Value="30"/> <Setter Property="Margin" Value="5"/> <Setter Property="FontSize" Value="14"/> <Setter Property="FontWeight" Value="Bold"/> <EventSetter Event="Click" Handler="MenuButton_Clicked"/> </Style> </StackPanel.Resources> <Button Style="{StaticResource styButton}" Content="Customers" Width="150"/> <Button Style="{StaticResource styButton}" Content="Orders"/> <Button Style="{StaticResource styButton}" Content="Inventory"/> <Button Content="Maintenance" Width="75" Height="25" Click="Maintenance_Clicked"/> </StackPanel>
The Style
defines the Button
properties Width, Height, Margin, FontSize
, and FontWeight ...
Get WPF Programmer's Reference: Windows Presentation Foundation with C# 2010 and .NET 4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.