Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

xaml

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.

like image 428
26071986 Avatar asked Jun 29 '11 14:06

26071986


2 Answers

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.

like image 180
H.B. Avatar answered Nov 15 '22 19:11

H.B.


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>
like image 33
Navid Rahmani Avatar answered Nov 15 '22 18:11

Navid Rahmani