views:

364

answers:

2

Hi There

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

+1  A: 

This seems to answer a similar question to yours: http://stackoverflow.com/questions/1366598/apply-style-to-all-treeviewitem

If that doesn't work then I'm not too sure about how it would be done in XAML but you could add the style in the code-behind with:

Control element;

for (int i = 0; i < Grid1.Children.Count; i++)
{
    element = (Control) Grid1.Children[i];
    element.Style = (Style) FindResource("DefaultMargins");
}

Edit: Grid1 refers to a x:Name="Grid1" property added to the XAML grid (poor naming I know).

Martin