Two Ways To Use Style On Controls In WPF Application

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,

  • ‘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.
    1. <Style x:Key="RedGradientBtn" TargetType="Button">  
    2. <Setter Property="Control.Foreground" Value="White" />  
    3. <Setter Property="Control.Background" Value="Maroon" />  
    4. </Style>  

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