Apply Style to all child-elements of specific type

大城市里の小女人 提交于 2019-12-23 04:05:22

问题


I want to write a style for wpf where all buttons in a StatusBar (that has a defined style) have the same style (e.g. width).

Here is what my style looks like:

<Style TargetType="{x:Type StatusBar}"
               x:Key="DialogBoxStatusBarStyle">
    <Setter Property="Background"
                    Value="LightGray" />
    <Setter Property="Padding"
                    Value="5" />

    ...?

</Style>

And the xaml for the elements:

<StatusBar Style="{StaticResource ResourceKey=DialogBoxStatusBarStyle}" Grid.Row="3"
               FlowDirection="RightToLeft">
        <Button Content="Übernehmen"
                Width="100"
                HorizontalAlignment="Right" />
        <Button Content="Abbrechen"
                Width="100"
                HorizontalAlignment="Right" />

        <Button Content="OK"
                Width="100"
                HorizontalAlignment="Right" />
    </StatusBar>

In the final version I don't want to set width to 100 for all buttons. This should be defined in the style of the StatusBar or better say in the style of the button-childs of the StatusBar.


回答1:


You could add a default Style for Buttons to the Resources of your DialogBoxStatusBarStyle:

<Style TargetType="StatusBar" x:Key="DialogBoxStatusBarStyle">
    <Style.Resources>
        <Style TargetType="Button">
            <Setter Property="Width" Value="100"/>
        </Style>
    </Style.Resources>
    ...
</Style>



回答2:


To extend on the answer above (@Clemens), you could even do something like this, to reuse a button style independently, and also apply it to children of a specific container.

Styles:

<Style TargetType="{x:Type Button}" x:Key="MyButtonStyle">
    <Setter Property="Width" Value="100" />
    <Setter Property="HorizontalAlignment" Value="Right" />
</Style>

<Style TargetType="{x:Type StatusBar}" x:Key="DialogBoxStatusBarStyle">
    <Setter Property="Background" Value="LightGray" />
    <Setter Property="Padding" Value="5" />

    <Style.Resources>
        <Style TargetType="{x:Type Button}" BasedOn="{StaticResource MyButtonStyle}" />
    </Style.Resources>
    ...
</Style>


来源:https://stackoverflow.com/questions/14319079/apply-style-to-all-child-elements-of-specific-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!