WPF container: equal width for items but spaced

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

I would not want to set a marker for the buttons. Is there any combination of containers and / or their properties that will help me achieve this?

I tried using StackPanel, UniformGrid, a simple grid, but without success - either I get huge buttons (albeit equal in width), or I get a gap between the buttons, but they have different widths.

+6
source share
3 answers

Using ItemsControl in combination with some kind of panel seems to be the cleanest solution for me. (As already mentioned, UniformGrid may be a good choice), for example:

<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 interval layout is handled by the element control rather than manually applied to the content. The content can then be any element of the FrameworkElement, and the span will still apply.

+10
source

It is easier to set margin for all Button in 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> 
+6
source

Use UniformGrid, set the Width parameter to whatever you like, and their HorizonatalAlignment / VerticalAlignment to Center.

This will save the buttons in a fixed size and change the interval when resizing the container, while maintaining the distance between the buttons

+2
source

Source: https://habr.com/ru/post/891646/


All Articles