There are 2 ways to perform style on a control in WPF application,
- Using separate style file
- Add the style on the same page
Now I will show you a demo to access the style on a button using both ways.
Note: In this article I am using Visual Studio 2015.
Step 1 - Create a project named ‘WpfTestApplication’ of WPF application.
Step 2 - It’s a better approach to create the folder named ‘css’ in the project to store the style files.
Step 3 - Add a Resource Dictionary named ‘MyStyle.xaml’ in the css folder.
Step 4 - Add the below code in ResourceDictionary tag, where,
- ‘Key’ is the style’s unique name.
- ‘TargetType’ tells about the target control type.
- In the setter, property means what behavior you want to change.
- In the setter, value means what will be the value of behavior.
- <Style x:Key="RedGradientBtn" TargetType="Button">
- <Setter Property="Control.Foreground" Value="White" />
- <Setter Property="Control.Background" Value="Maroon" />
- </Style>
Step 5 - Add the code into the auto generated page named ‘MainWindow.xaml’ to access the resource dictionary file which exists in the css folder means MyStyle.xaml file.
- <Window.Resources>
- <ResourceDictionary>
- <ResourceDictionary.MergedDictionaries>
- <ResourceDictionary Source="/WpfTestApplication;component/css/MyStyle.xaml">
- </ResourceDictionary>
- </ResourceDictionary.MergedDictionaries>
- </ResourceDictionary>
- </Window.Resources>
After that add a button on the page with some content, height and width including the style like,
- <Button Content="My Button" Height="50" Width="100" Style="{StaticResource RedGradientBtn}"/>
Note - In button style, ‘RedGradientBtn’ is the unique key name which I have already defined in the MyStyle.xaml file.
Step 6 - When I run the page, it will look like,
You can also add the style of MyStyle.xaml in the ‘MainWindow.xaml’ page without adding any other file.
- <Window.Resources>
- <ResourceDictionary>
- <Style x:Key="RedGradientBtn" TargetType="Button">
- <Setter Property="Control.Foreground" Value="White" />
- <Setter Property="Control.Background" Value="Maroon" />
- </Style>
- </ResourceDictionary>
- </Window.Resources>
- And then add button
- <Button Content="My Button" Height="50" Width="100"
- Style="{StaticResource RedGradientBtn}"/>
The same output will show,