将样式应用于 WPF 中的所有派生类 [英] Applying a style to all derived classes in WPF
本文介绍了将样式应用于 WPF 中的所有派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对从 Control 派生的所有类应用一种样式.WPF可以做到这一点吗?以下示例不起作用.我希望标签、文本框和按钮的边距为 4.
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>
推荐答案
这是一个解决方案:
<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 中的所有派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文