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.
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), eg:
<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.
在UniformGrid
为所有Button
设置边界更容易:
<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>
Use a UniformGrid, set the button's Width to whatever you like and their HorizonatalAlignment/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
链接地址: http://www.djcxy.com/p/50066.html