WPF通过父样式为子项自动分配样式

时间:2016-04-13 05:53:56

标签: c# wpf xaml xaml-resources

我的应用程序中有几个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>

有没有其他方法可以做到这一点,而无需在每个孩子上设置样式并重复赋值样式?

1 个答案:

答案 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>