Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a style to all derived classes in WPF

Tags:

styles

wpf

xaml

I want to apply a style to all classes derived from Control. Is this possible with WPF? The following example does not work. I want the Label, TextBox and Button to have a Margin of 4.

<Window x:Class="WeatherInfo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Wetterbericht" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="Control">
            <Setter Property="Margin" Value="4"/>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel Margin="4" HorizontalAlignment="Left">            
            <Label>Zipcode</Label>
            <TextBox Name="Zipcode"></TextBox>
            <Button>get weather info</Button>
        </StackPanel>
    </Grid>
</Window>
like image 562
Sebastian Avatar asked Oct 20 '09 06:10

Sebastian


2 Answers

Here's one solution:

<Window.Resources>
    <Style TargetType="Control" x:Key="BaseStyle">
        <Setter Property="Margin" Value="4"/>
    </Style>
    <Style BasedOn="{StaticResource BaseStyle}" TargetType="Button" />
    <Style BasedOn="{StaticResource BaseStyle}" TargetType="Label" />
    <Style BasedOn="{StaticResource BaseStyle}" TargetType="TextBox" />
</Window.Resources>
<Grid>
    <StackPanel Margin="4" HorizontalAlignment="Left">
        <Label>Zipcode</Label>
        <TextBox Name="Zipcode"></TextBox>
        <Button>get weather info</Button>
    </StackPanel>
</Grid>
like image 141
Carlo Avatar answered Oct 13 '22 00:10

Carlo


This is not possible in WPF. You have a couple of options to help you out:

  1. Create one style based on another by using the BasedOn attribute.
  2. Move the common information (margin, in this case) into a resource and reference that resource from each style you create.

Example of 1

<Style TargetType="Control">
    <Setter Property="Margin" Value="4"/>
</Style>

<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type Control}}">
</Style>

Example of 2

<Thickness x:Key="MarginSize">4</Thickness>

<Style TargetType="TextBox">
    <Setter Property="Margin" Value="{StaticResource MarginSize}"/>
</Style>
like image 30
Kent Boogaart Avatar answered Oct 12 '22 22:10

Kent Boogaart