Control Style in WPF

Control Styles in WPF are used to share the structure in a reusable format, which we can apply in most of our controls. These are the styles which we describe in a particular format and then we use it in our control according to our requirement. The Base is <Window.Resources> XML element which contains a <Style> XML element. The <Style> element contains the <Setter> XML elements. Here we take an example of the Button Control. In this program we set the Style of the Button with the help of a Style Attribute:

<Window x:Class="ControlStylesInWPF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width
="300">
    <Window.Resources>
        <Style x:Key="BoldStyle">
            <Setter Property="Control.FontSize" Value="10" />
                <Setter Property="Control.FontWeight" Value="Bold" />
                    <Setter Property="Control.BorderThickness" Value="1" />

        </Style>
        <Style x:Key="SmallStyle">
            <Setter Property="Control.FontSize" Value="5" />
                <Setter Property="Control.FontWeight" Value="Normal" />
                    <Setter Property="Control.BorderThickness" Value="2" />
        </Style>
    </Window.Resources>
    <Grid>
        <Button
Style="{StaticResource SmallStyle }"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Grid.Column="0"
Grid.ColumnSpan="1"
Grid.Row="0"
Grid.RowSpan="1"
Margin="43,61,0,0"
Width="75"
Height="23"
Name="btnClick">Click
       
</Button>
    </Grid>
</
Window>

In this example we set the Style Attribute of the Button to SmallStyle:

Style="{StaticResource SmallStyle }"

Here is the output:

CntrlStyWPF1.gif

And if we set it to BoldStyle:

Style="{StaticResource BoldStyle }"

CntrlStyWPF2.gif

We can also set it programmatically:

Here we first define a Click Event on the Button Control:

<Grid>
        <Button
Style="{StaticResource BoldStyle }"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Grid.Column="0"
Grid.ColumnSpan="1"
Grid.Row="0"
Grid.RowSpan="1"
Margin="43,61,0,0"
Width="75"
Height="23"
Name="btnClick" Click="MyFirstClick">Click
       
</Button>
    </Grid>

And then we write the EventHandler in the .cs page:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }
    private void MyFirstClick(object sender, RoutedEventArgs e)
    {
        btnClick.Style = (Style)FindResource("BoldStyle");
    }
}


To change the style SmallStyle To BoldStyle programmatically:

CntrlStyWPF3.gif

After click:

CntrlStyWPF4.gif