2009-10-20 23 views
7

Deseo aplicar un estilo a todas las clases derivadas de Control. ¿Es esto posible con WPF? El siguiente ejemplo no funciona. Quiero que Label, TextBox y Button tengan un Margen de 4.Aplicación de un estilo a todas las clases derivadas en WPF

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

Respuesta

10

Aquí hay una solución:

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

funciona como un encanto ... Gracias. – Sebastian

6

Esto no es posible en WPF. Tiene un par de opciones para ayudarlo:

  1. Cree un estilo basado en otro utilizando el atributo BasedOn.
  2. Mueva la información común (margen, en este caso) a un recurso y haga referencia a ese recurso de cada estilo que cree.

Ejemplo de 1

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

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

Ejemplo de 2

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

<Style TargetType="TextBox"> 
    <Setter Property="Margin" Value="{StaticResource MarginSize}"/> 
</Style> 
Cuestiones relacionadas