容器内的隐式样式 [英] Implicit Style Within Container
问题描述
我想将 Padding="0"
应用到左侧边栏上的每个 Label
(第一个 StackPanel
),以便它离开-与每个 TextBox
(和其他控件)对齐.
I want to apply Padding="0"
to each Label
on the left sidebar (the first StackPanel
) so that it left-aligns with each TextBox
(and other controls).
如何在
中定义仅适用于特定容器中的元素的隐式样式?
How can I define an implicit style in <ApplicationResources>
which only applies to elements within a specific container?
替代方案:
- 使用
x:Key="sidebarLabel"
.但是,对于我的实际应用程序侧边栏中的许多标签而言,此选项似乎是多余的. - 将
Padding=0
添加到侧栏中的每个Label
.这与之前的替代方案基本相同. - 将隐式样式移动到
中.但是,我希望将样式(在App.xaml
中)与 XAML(在MainWindow.xaml
中)分开.
- Use
x:Key="sidebarLabel"
. However, this option seems redundant for the many labels in the sidebar of my actual application. - Add
Padding=0
to eachLabel
in the sidebar. This is essentially the same as the previous alternative. - Move the implicit style into
<StackPanel.Resources>
. However, I want to keep the styles (inApp.xaml
) separate from the XAML (inMainWindow.xaml
).
<Application.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Padding" Value="0" />
</Style>
</Application.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<GroupBox Header="New User">
<StackPanel>
<Label>First Name:</Label>
<TextBox/>
<Label>Last Name:</Label>
<TextBox/>
</StackPanel>
</GroupBox>
</StackPanel>
<GroupBox Grid.Column="1" Header="Main">
<StackPanel>
<Label>I want default padding here</Label>
</StackPanel>
</GroupBox>
</Grid>
推荐答案
你可以像这样在 app.xaml 中使用 Style.Resources
:
you can use Style.Resources
in app.xaml like this:
<Application.Resources>
<Style TargetType="StackPanel">
<Style.Resources>
<Style TargetType="Label">
<Setter Property="Padding" Value="0" />
</Style>
</Style.Resources>
</Style>
</Application.Resources>
这会设置在 StackPanel
中使用的所有 Label.Style
.如果您只想向特定 StackPanels
中的标签提供此行为,您可以像这样使用 x:Key
:
this sets all Label.Style
, that are used inside a StackPanel
. If you like to provide this behaviour only to labels in specific StackPanels
you can use a x:Key
like this:
<Application.Resources>
<Style TargetType="StackPanel" x:Key="LabelStyledPanel">
<Style.Resources>
<Style TargetType="Label">
<Setter Property="Padding" Value="0" />
</Style>
</Style.Resources>
</Style>
</Application.Resources>
然后所有使用 StaticResource LabelStyledPanel
的 StackPanels
使用标签样式.
then all StackPanels
using StaticResource LabelStyledPanel
use the label style.
这篇关于容器内的隐式样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!