tags:

views:

335

answers:

2

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>
+3  A: 

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>

HTH, Kent

Kent Boogaart
+2  A: 

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>
Carlo
works like a charm... Thank you.
Sebastian