开发者

Applying a style to all derived classes in WPF

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>


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>


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜