Applying a style to all derived classes in WPF
我想将样式应用于从Control派生的所有类。 使用WPF可以做到吗?
以下示例不起作用。 我希望Label,TextBox和Button的边距为4。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <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> |
这是一种解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <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> |
在WPF中这是不可能的。 您有几种选择可以帮助您:
示例1
1 2 3 4 5 6 | <Style TargetType="Control"> <Setter Property="Margin" Value="4"/> </Style> <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type Control}}"> </Style> |
例子2
1 2 3 4 5 | <Thickness x:Key="MarginSize">4</Thickness> <Style TargetType="TextBox"> <Setter Property="Margin" Value="{StaticResource MarginSize}"/> </Style> |