Apollo-Roboto
Apollo-Roboto

Reputation: 780

WPF How to set a UniformGrid spacing between colums and rows

Is it possible to set a specific spacing between columns and rows on a UniformGrid?

the default behavior of a UniformGrid is this:

<UniformGrid Columns="2" Rows="2">
    <Button Content="1"/>
    <Button Content="2"/>
    <Button Content="3"/>
    <Button Content="4"/>
</UniformGrid>

normal

But I'd like it to look like this instead:

what I want

Upvotes: 1

Views: 2544

Answers (1)

thatguy
thatguy

Reputation: 22079

No, not directly in the UniformGrid, but you can add a Margin to its children. If you need the same spacing for multiple children, just extract them to a style. For your example, it would look like this:

<UniformGrid Columns="2" Rows="2">
   <Button Content="1" Margin="0, 0, 10, 10"/>
   <Button Content="2" Margin="10, 0, 0, 10"/>
   <Button Content="3" Margin="0, 10, 10, 0"/>
   <Button Content="4" Margin="10, 10, 0, 0"/>
</UniformGrid>

In general, if you do not want to define styles for each control and you want uniform spacing for child controls, you can nest them in Borders and apply a common style for margins to it.

<UniformGrid Rows="1" Columns="3">
   <UniformGrid.Resources>
      <Style x:Key="BorderSpacingStyle" TargetType="{x:Type Border}">
         <Setter Property="Margin" Value="10"/>
      </Style>
   </UniformGrid.Resources>
   <Border Style="{StaticResource BorderSpacingStyle}">
      <Button Content="0"/>
   </Border>
   <Border Style="{StaticResource BorderSpacingStyle}">
      <Button Content="1"/>
   </Border>
   <Border Style="{StaticResource BorderSpacingStyle}">
      <Button Content="2"/>
   </Border>
</UniformGrid>

Upvotes: 3

Related Questions