WPF容器:元素的宽度相等,但它们之间有间距

时间:2011-06-29 14:46:40

标签: c# wpf xaml

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

我不想为按钮设置保证金。是否有任何容器和/或其属性的组合,这将有助于我实现这一目标?

我尝试过使用StackPanel,UniformGrid,简单网格,但没有成功 - 要么我得到巨大的按钮(虽然宽度相等),或者我最终得到按钮之间的间距,但它们有不同的宽度。

3 个答案:

答案 0 :(得分:13)

将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,间距仍然适用。

答案 1 :(得分:8)

Button中的所有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>

答案 2 :(得分:3)

使用UniformGrid,将按钮的宽度设置为您喜欢的任何宽度,并将其Horizo​​natalAlignment / VerticalAlignment设置为Center。

这将使按钮保持固定大小并在调整容器大小时更改间距,同时保持按钮之间的间距相同