我想要一个只有四个按钮的容器。按钮应该水平对齐,具有相同的宽度,不填满所有可用空间并且它们之间的间距相等。
我不想为按钮设置边距。是否有任何容器和/或其属性的组合可以帮助我实现这个目标?
我试过使用 StackPanel、UniformGrid、简单的网格,但没有成功——要么我得到了巨大的按钮(尽管宽度相等),要么我最终在按钮之间留有间距,但它们的宽度不同。
最佳答案
将 ItemsControl 与某种面板结合使用对我来说似乎是最干净的解决方案。 (如前所述,UniformGrid 可能是一个不错的选择),例如:
<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>
这样做的好处是间距布局由项目控件处理,而不是手动施加到内容上。此外,内容可以是任何 FrameworkElement,间距仍然适用。
关于c# - WPF 容器 : equal width for elements but with spacing between them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6522596/