26071986
26071986

Reputation: 2330

WPF Container: equal width for elements but with spacing between them

I'd like to have a container with only four buttons in it. Buttons should be aligned horizontally, have the same width, not fill all the available space and have equal space between them.

I would not like to set margin for buttons. Is there any combination of containers and/or their properties, that will help me to achieve this goal?

I've tried using StackPanel, UniformGrid, simple Grid, but with no success - either I get huge buttons (though equal in width), or I end up with spacing between buttons, but they have different width.

Upvotes: 12

Views: 17522

Answers (3)

Nir
Nir

Reputation: 29594

Use a UniformGrid, set the button's Width to whatever you like and their HorizontalAlignment/VerticalAlignment to Center.

This will keep the buttons in a fixed size and change the spacing when you resize the container while keeping the spacing the same between buttons.

Upvotes: 3

brunnerh
brunnerh

Reputation: 184516

Using an ItemsControl in combination with some kind of panel seems like the cleanest solution to me. (As mentioned the UniformGrid might be a good choice), e.g.:

<ItemsControl>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="FrameworkElement.Margin" Value="5"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.Items>
        <Button Content="Button"/>
        <Button Content="Button"/>
        <Button Content="Button"/>
        <Button Content="Button"/>
    </ItemsControl.Items>
</ItemsControl>

This has the advantage that the spacing layout is handled by the items control rather than being manually inflicted on the contents. Further the content can be any FrameworkElement and the spacing will still apply.

Upvotes: 19

Navid Rahmani
Navid Rahmani

Reputation: 7958

It's easier to set margin for all Buttons in a UniformGrid:

<UniformGrid Columns="4" Rows="1">
   <UniformGrid.Resources>
      <Style TargetType="{x:Type Button}">
         <Setter Property="Margin" Value="2"/>
      </Style>
   </UniformGrid.Resources>

   <Button/>
   <Button/>
   <Button/>
   <Button/>
</UniformGrid>

Upvotes: 11

Related Questions