WPF容器:元素等宽但之间有间距

12

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

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

我尝试使用StackPanel、UniformGrid和简单的Grid,但都没有成功 - 要么得到巨大的按钮(虽然宽度相等),要么在按钮之间留下间隔,但它们的宽度不同。


你想要:1. 按钮具有固定大小,而它们之间的空间在容器调整大小时增长/缩小 2. 具有固定间距,而按钮会自动调整大小或3. 保持按钮和空间成比例,并一起调整大小? - Nir
1
为什么你不喜欢使用边距? - Navid Rahmani
3个回答

19

在我看来,使用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,间距仍然适用。


11

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>

3
使用UniformGrid,将按钮的宽度设置为所需大小,并将它们的HorizontalAlignment/VerticalAlignment设置为Center。
这将使按钮保持固定大小,在调整容器大小时更改间距,同时保持按钮之间的间距不变。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接