Setting the various properties of a control is the simplest way to alter its look and enables us to make either minor or more dramatic changes to it. As most UI elements extend the Control class, they mostly share the same properties that affect their appearance and alignment. When defining styles for controls, we should specify their type in the TargetType property, as this helps the compiler to verify that the properties that we are setting actually exist in the class:
<Button Content="Go"> <Button.Style> <Style TargetType="{x:Type Button}"> <Setter Property="Foreground" Value="Green" /> <Setter Property="Background" Value="White" /> </Style> </Button.Style> </Button>
Failing to do so will result in the compiler stating that the member is not recognized or is not accessible. In these cases, we will need to specify the class type as well, in the format ClassName.PropertyName:
<Button Content="Go"> <Button.Style> <Style> <Setter Property="Button.Foreground" Value="Green" /> <Setter Property="Button.Background" Value="White" /> </Style> </Button.Style> </Button>
One really useful property that the Style class declares is the BasedOn property. Using this property, we can base our styles on other styles and this enables us to create a number of incrementally different versions. Let's highlight this with an example:
<Style x:Key="TextBoxStyle" TargetType="{x:Type TextBox}"> <Setter Property="SnapsToDevicePixels" Value="True" /> <Setter Property="Margin" Value="0,0,0,5" /> <Setter Property="Padding" Value="1.5,2" /> <Setter Property="TextWrapping" Value="Wrap" /> </Style> <Style x:Key="ReadOnlyTextBoxStyle" TargetType="{x:Type TextBox}" BasedOn="{StaticResource TextBoxStyle}"> <Setter Property="IsReadOnly" Value="True" /> <Setter Property="Cursor" Value="Arrow" /> </Style>
Here, we define a simple style for the textboxes in our application. We name it TextBoxStyle and then reference it in the BasedOn property of the second style. This means that all of the property setters and triggers declared in the first style will also apply to the bottom style. In the second style, we add a few further setters to make the applied textbox read-only.
One last point to note is that if we wanted to base a style on the default style of a control, we can use the value that we normally enter into the TargetType property as the key to identify the style that we want to base the new style on:
<Style x:Key="ExtendedTextBoxStyle" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"> ... </Style>
Let's now move on to take a deeper look into resources.