Skip to main content

...

....

C# WPF Tutorial - The BasedOn Style Property [Beginner]


By this point, everybody knows and (mostly) loves styles in WPF. They give you the ability to customize and control from a high level - letting you abstract out the look of a control from the actual instantiation of a control. At this point I don't know how many times I've heard WPF styles referred to as "CSS, but for your application!" - and in many ways, that statement is right (although the cascading bit in WPF doesn't always work as well as CSS). Today we are going to take a look at a property of styles that can give you even more power to abstract away how your application looks - the BasedOnProperty.

The BasedOn property of a style lets you essentially do style inheritance (something I often wish CSS let you do in a much less cumbersome manner). It lets you "base" a style off of another style - you get all the settings of the base style, and then you add to them or override them as you see fit. This is great for when you have an overall generic style for a control, but you want to customize certain aspects for certain areas of your application

Below we have a screenshot of a little WPF application with 4 buttons, showing off some style inheritance. The first button is using a style that sets the background to a gradient, along with a couple other properties. The second button uses a style that inherits from the first button's style, and then sets the foreground color to red. The third button used a completely different style that doesn't inherit from anything, and sets the foreground color to green. And the final button inherits its style from the red foreground color button, and then sets the horizontal alignment to right.

BasedOn Style Test Screenshot

OK, now that we have that picture and the paragraph description of the picture out of the way, let's look at the code behind it. First, the style for that first button:
<Style TargetType="{x:Type Button}">
  <Setter Property="Background">
    <Setter.Value>
      <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
        <LinearGradientBrush.GradientStops>
          <GradientStop Color="#FFFFFF" Offset="0" />
          <GradientStop Color="#E0E5EB" Offset=".4" />
          <GradientStop Color="#CBD5DF" Offset=".4" />
          <GradientStop Color="#FFFFFF" Offset="1" />
        </LinearGradientBrush.GradientStops>
      </LinearGradientBrush>
    </Setter.Value>
  </Setter>
  <Setter Property="MinHeight" Value="25" />
</Style>
 
A pretty standard style - setting two properties, the Background and the MinHeight. Probably the only interesting thing to note here is that we are not giving it a x:Key value. Because of this, this button style will apply to all buttons (within the scope of where this style is declared) that do not have their style explicitly set.

Next, the first style that inherits:
<Style TargetType="{x:Type Button}" 
    BasedOn="{StaticResource {x:Type Button}}" 
    x:Key="RedTextBasedOnButton">
  <Setter Property="Foreground" Value="Red" />
</Style>
 
Now we are setting a value for the BasedOn property. Because we are basing this style on a style that does not explicitly have a key, we use the value {StaticResource {x:Type Button}}. This is because when the x:Key is not explicitly set for a style, it gets implicitly set to the style's target type - in this case {x:Type Button}. By setting the BasedOn property to this, we get the Background and MinHeight values defined in that style.

One other thing to note - this time we are setting a value for x:Key - we only want this style to apply to buttons that have their style set to "RedTextBasedOnButton".

OK, now for that green text style:
<Style TargetType="{x:Type Button}" x:Key="GreenTextButton">
  <Setter Property="Foreground" Value="Green" />
</Style>
 
This style isn't based on anything, so the only thing this style will do is set the foreground color to green. Not very interesting.

And finally, the right align style.
<Style TargetType="{x:Type Button}" x:Key="RedTextRightButton"
    BasedOn="{StaticResource RedTextBasedOnButton}">
  <Setter Property="HorizontalContentAlignment" Value="Right" />
  <Setter Property="MinHeight" Value="40" />
</Style>
 
Here, the BasedOn property is set to {StaticResource RedTextBasedOnButton}. This means that this style will inherit everything that RedTextBasedOnButton does, which in turn inherits everything that the {x:Type Button} does. This means that you can make style inheritance trees as deep as you want - WPF will just follow up the chain gathering properties as it goes.

Oh, and there is one other thing this style shows off. See how it sets the MinHeight? This value will override the value in the base {x:Type Button}, as you might expect. This means that you can always override properties set by styles you are based on.

So that is all the special style code. Below is the code for the entire window (there isn't a whole lot more to it than those styles):
<Window x:Class="WPFBasedOnStyle.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="BasedOn Style Test" Height="150" Width="400">
  <Window.Resources>
    <Style TargetType="{x:Type Button}">
      <Setter Property="Background">
        <Setter.Value>
          <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
            <LinearGradientBrush.GradientStops>
              <GradientStop Color="#FFFFFF" Offset="0" />
              <GradientStop Color="#E0E5EB" Offset=".4" />
              <GradientStop Color="#CBD5DF" Offset=".4" />
              <GradientStop Color="#FFFFFF" Offset="1" />
            </LinearGradientBrush.GradientStops>
          </LinearGradientBrush>
        </Setter.Value>
      </Setter>
      <Setter Property="MinHeight" Value="25" />
    </Style>
    <Style TargetType="{x:Type Button}" x:Key="RedTextBasedOnButton"
        BasedOn="{StaticResource {x:Type Button}}">
      <Setter Property="Foreground" Value="Red" />
    </Style>
    <Style TargetType="{x:Type Button}" x:Key="GreenTextButton">
      <Setter Property="Foreground" Value="Green" />
    </Style>
    <Style TargetType="{x:Type Button}" x:Key="RedTextRightButton"
        BasedOn="{StaticResource RedTextBasedOnButton}">
      <Setter Property="HorizontalContentAlignment" Value="Right" />
      <Setter Property="MinHeight" Value="40" />
    </Style>
  </Window.Resources>
  <StackPanel>
    <Button Content="I'm a Styled Button" />
    <Button Style="{StaticResource RedTextBasedOnButton}"
        Content="I'm a Red Text Button Based On Styled Button" />
    <Button Style="{StaticResource GreenTextButton}"
        Content="I'm a Green Text Button" />
    <Button Style="{StaticResource RedTextRightButton}"
        Content="I'm a Right Align Button Based on Red Text Button" />
  </StackPanel>
</Window>
 
I hope that answered any questions you had on the BasedOn property of Styles, but if you have any more, feel free to leave them below.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV