C# – WPF – Changing styles in WPF (Setter Property usage / Style declaration in XAML)

With the current post I will present a simple application, which changes styles of buttons within WPF, based on our selection. In order to change the styles of the design, we define both styles as variables in the XAML code. Thus, our XAML (the content of MainWindow.xaml) looks like this:

This code can be divided into two main parts – the part, declared between the tags <Window.Resources></> and the part, declared in the <StackPanel></> part.

In the first part, we declare two styles, which would be later assigned to the controls. The first style has green background of the control and the second style – white background. In the second part we create the following controls:

  • button (named bu)
  • checkbox (named cb)
  • independent button (w/o name, because we do not need to access it)
  • textbox (named tb)
  • separator (named sp)

At the end we embed a stack panel in the current one, containing two radio buttons, used to run our application. The default button runs the C# method (rb1_Checked) and the button with text “styleB” runs rb2_Checked.

So, after we run the application, we get the following two options:


How does it work? The secret is in the C# code 🙂 here:

What does it do? The needed “InitializeComponent” is a must in the MainWindow() method. The rest are the methods, run upon a change of the radio buttons. A good example for programming code is the following line:

It tells to the compiler, to find a style resource named “styleA” somewhere in the program and to assign it to the variable “st” from type Style. Then with the naming of the buttons, which was created in XAML, we access them in C# and we give them the resource, which we just found. Wonderful, eh? 🙂

If you want to try this out, you may download this application from here.

Anyway, I would advise you to create it by yourself, as far as you have the complete code.

Enjoy it!