Wpf – Applying WPF styles to Child Items

gridstyleswpf

Lets say I have a grid, within my grid I have a number of controls. Instead of setting the margin for each of these controls, I wish to create a style to set the margin for ANY control I drop into a grid. Is this possible?

I was hoping that the following would work:

<Window.Resources>
    <Style x:Key="DefaultMargins">
        <Setter Property="Control.Margin" Value="3, 3, 3, 3"/>
        <Setter Property="Control.FontSize" Value="50"/>
    </Style>
</Window.Resources>
<Grid Style="{StaticResource DefaultMargins}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="3*"/>
        <RowDefinition Height="3*"/>
    </Grid.RowDefinitions>
    <Button Grid.Row="0" Grid.Column="0" Name="button1">Button</Button>
</Grid>

But the Margin is ignored, it not supporting property value inheritance. Is there a simple alternative to apply the margins to each 'child' of the grid? I understand that it is possible to achieve this sort of thing in CSS and some of our developers are interested in using this sort of construct.

Thanks
Ian

Best Answer

You can specify the style by type and constrain it to the scope of the Grid:

    <Grid>
<Grid.Resources>
    <Style TargetType="{x:Type Control}">
        <Setter Property="Control.Margin" Value="3, 3, 3, 3"/>
        <Setter Property="Control.FontSize" Value="50"/>
    </Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="3*"/>
    <ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="3*"/>
    <RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Grid.Column="0" Name="button1">Button</Button>

Related Topic