首页 文章

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

提问于
浏览
7

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

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

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

3 回答

  • 8

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

  • 3

    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>
    
  • 13

    使用UniformGrid,将按钮的宽度设置为您喜欢的任何宽度,并将其HorizonatalAlignment / VerticalAlignment设置为Center .

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

相关问题