c# - WPF 容器 : equal width for elements but with spacing between them

标签 c# wpf xaml

我想要一个只有四个按钮的容器。按钮应该水平对齐,具有相同的宽度,不填满所有可用空间并且它们之间的间距相等。

我不想为按钮设置边距。是否有任何容器和/或其属性的组合可以帮助我实现这个目标?

我试过使用 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/

相关文章:

c# - 有人如何在 C# 中编写 "macro"?

javascript - 从 Javascript 到 HTML 的值不会在服务器端读取

c# - 使用泛型的 LINQ 连接

c# - 在 TextBlock 中运行秒表

xaml - UWP C++ 中的通用工具栏

wpf - 将 ViewModel 放在代码隐藏中是错误的吗?

c# - 如何在 C# 中将 float 向上舍入到最接近的整数?

c# - 为什么此代码会导致 "The name does not exist in the current context"错误?

wpf - 样式 WPF/Silverlight 组合框

不显示透明 winform 内的 WPF 控件