Updated on Kisan Patel
Styles in WPF allow you to apply a set of properties to more than one element.
For example, you can change the style of the TextBlock control by chaning its FontSize and FontFamily properties. However, if you want your TextBlock control to share some properties, you can create a common style for them.
If you declare the style in the root element of an application (App.xaml), the style can be used anywhere in the application. If you declare the style in one of the application’s XAML files, then the style can be used in that XAML file only.
You can bind a style to a control by using the Style property.
<Style x:Key="myButton"> <Setter Property="Button.Background" Value="Green"></Setter> <Setter Property="Button.Foreground" Value="White"></Setter> </Style>
Lets add the below line of XAML code to the MainWindow.xaml file:
<Window x:Class="WPFResourceDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.Resources> <Style x:Key="myButton"> <Setter Property="Button.Background" Value="Green"></Setter> <Setter Property="Button.Foreground" Value="White"></Setter> <Setter Property="Button.Width" Value="250"></Setter> <Setter Property="Button.Height" Value="40"></Setter> <Setter Property="Button.FontSize" Value="22"></Setter> </Style> </Grid.Resources> <Button Content="Change color" Style="{StaticResource myButton}"/> </Grid> </Window>
The output of the above XAML code will be: