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

260*_*986 7 c# wpf xaml

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

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

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

H.B*_*.B. 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>
Run Code Online (Sandbox Code Playgroud)

这具有以下优点:间隔布局由物品控制处理而不是手动地对内容施加.此外,内容可以是任何FrameworkElement,间距仍然适用.


Nav*_*ani 8

Button在以下情况下为所有s 设置边距更容易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>
Run Code Online (Sandbox Code Playgroud)