There are 2 ways to perform style on a control in WPF application,

  1. Using separate style file
  2. 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.

WpfTestApplication

Step 2 - It’s a better approach to create the folder named ‘css’ in the project to store the style files.

style

Step 3 - Add a Resource Dictionary named ‘MyStyle.xaml’ in the css folder.

Resource Dictionary

Step 4 - Add the below code in ResourceDictionary tag, where,

code

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.

  1. <Window.Resources>
  2. <ResourceDictionary>
  3. <ResourceDictionary.MergedDictionaries>
  4. <ResourceDictionary Source="/WpfTestApplication;component/css/MyStyle.xaml">
  5. </ResourceDictionary>
  6. </ResourceDictionary.MergedDictionaries>
  7. </ResourceDictionary>
  8. </Window.Resources>
After that add a button on the page with some content, height and width including the style like,
  1. <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.

code

Step 6 - When I run the page, it will look like,

page

You can also add the style of MyStyle.xaml in the ‘MainWindow.xaml’ page without adding any other file.
  1. <Window.Resources>
  2. <ResourceDictionary>
  3. <Style x:Key="RedGradientBtn" TargetType="Button">
  4. <Setter Property="Control.Foreground" Value="White" />
  5. <Setter Property="Control.Background" Value="Maroon" />
  6. </Style>
  7. </ResourceDictionary>
  8. </Window.Resources>
  9. And then add button
  10. <Button Content="My Button" Height="50" Width="100"
  11. Style="{StaticResource RedGradientBtn}"/>
The same output will show,

page