将样式应用于WPF中的所有派生类
问题描述:
我想将样式应用于派生自Control的所有类。这可能与WPF? 以下示例不起作用。我希望标签,文本框和按钮的边距为4.将样式应用于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>
答
这里有一个解决方案:
<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中是不可能的。您有几个选项可以帮助您:
- 使用BasedOn属性创建基于另一个样式的一种样式。
- 将公共信息(本例中为边距)移动到资源中,并根据您创建的每种样式引用该资源。 例
1例
<Style TargetType="Control">
<Setter Property="Margin" Value="4"/>
</Style>
<Style TargetType="TextBox" BasedOn="{StaticResource {x:Type Control}}">
</Style>
<Thickness x:Key="MarginSize">4</Thickness>
<Style TargetType="TextBox">
<Setter Property="Margin" Value="{StaticResource MarginSize}"/>
</Style>
的作品就像一个魅力...谢谢你。 – Sebastian 2009-10-20 10:07:49