我的应用程序中有几个StackPanels
希望他们的孩子应用某些样式:
<StackPanel.Resources>
<Style TargetType="TextBlock" BasedOn="{StaticResource SettingLabel}" />
<Style TargetType="DockPanel" BasedOn="{StaticResource SettingRow}" />
<Style TargetType="CheckBox" BasedOn="{StaticResource SettingCheckBox}" />
<Style TargetType="PasswordBox" BasedOn="{StaticResource DialogPasswordBox}" />
<Style TargetType="TextBox" BasedOn="{StaticResource DialogTextBox}" />
</StackPanel.Resources>
我不是一遍又一遍地写下这5行,而是给StackPanel
本身一个将应用它们的风格,从而减少冗余。
无法在样式设置器中设置Resources
,因为它没有依赖属性:
<Style x:Key="SettingPanel" TargetType="StackPanel">
<Setter Property="Resources">
<Setter.Value>
<Style TargetType="TextBlock" BasedOn="{StaticResource SettingLabel}" />
<Style TargetType="DockPanel" BasedOn="{StaticResource SettingRow}" />
<Style TargetType="CheckBox" BasedOn="{StaticResource SettingCheckBox}" />
<Style TargetType="PasswordBox" BasedOn="{StaticResource DialogPasswordBox}" />
<Style TargetType="TextBox" BasedOn="{StaticResource DialogTextBox}" />
</Setter.Value>
</Setter>
</Style>
有没有其他方法可以做到这一点,而无需在每个孩子上设置样式并重复赋值样式?
答案 0 :(得分:3)
您可以在Style.Resources
StackPanel
中定义样式。这些将使用SettingPanel作为样式应用于StackPanel
的所有子项。
<Style x:Key="SettingPanel" TargetType="StackPanel">
<Style.Resources>
<Style TargetType="TextBlock" BasedOn="{StaticResource SettingLabel}" />
<Style TargetType="DockPanel" BasedOn="{StaticResource SettingRow}" />
<Style TargetType="CheckBox" BasedOn="{StaticResource SettingCheckBox}" />
<Style TargetType="PasswordBox" BasedOn="{StaticResource DialogPasswordBox}" />
<Style TargetType="TextBox" BasedOn="{StaticResource DialogTextBox}" />
</Style.Resources>
</Style>