WPF Styles

 Resource Styles

Styles can be specified in the window resource section.

<Window.Resources>
  <Style x:key="key" TargetType="x:Type controlType">
    <Setter Property="propertyName Value="value" />
    ...
  </Style>
</Window.Resources>

Which is applied as:

<controlName Style="{StaticResource key}" ...

Object Formatting

When objects are bound to a property of a control, the mechanism for formatting the display of their values is based on creating a template.
For example the ListBox supports an ItemTemplate:

<ListBox ItemsSource="{Binding}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="Binding path=..." />
      <TextBlock Text="Binding path=..." />
      ...
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Default Data Templates can also be specified for particular types:

<DataTemplate DataType="{x:Type lw:Move}">
	<Grid>
		<TextBlock
			Text="{Binding Path=Player}"
			VerticalAlignment="Center"
			HorizontalAlignment="Center" />
		<TextBlock
			Text="{Binding Path=MoveNo}"
			FontSize="16"
			FontStyle="Italic"
			VerticalAlignment="Bottom"
			HorizontalAlignment="Right"  
			Margin="2,2,4,2"/>

	</Grid>
</DataTemplate>

Where Move is a type in the namespace lw

Control Templates

The appearance of a control can be radically altered by the use of control templates that change the whole format of the control.

Again they can be defined in the resources for the form:

<Window.Resources>
  <Style x:key="styleName" TargetType="{x:Type controlName}">
    <Setter.Value>
      <ControlTemplate>
        ... controls to display ...
        <ControlTemplate.Triggers>
          ... trigger defs. ...
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Style>
  <ControlTemplate
</Window.Resources>

Occasionally Control templates require the TargetType attribute to be restated.

The triggers section allows dynamic behaviour to be added to the appearance – see the triggers section.

To allow the control to display content, a ContentPresenter element needs to be present in the template.

<Style TargetType="{x:Type Button}" BasedOn="{StaticResource FS}">
  <Setter Property="Background" Value="Orange" />
  <Setter Property="Template">
    <Setter.Value>
      <!-- wont work without respecifying the TargetType...?-->
      <ControlTemplate TargetType="{x:Type Button}">
        <Border Background="{TemplateBinding Property=Background}">
          <ContentPresenter/>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Leave a Reply