如何使工具栏按钮共享相同的宽度?

How to make toolbar buttons share same width?

我有一个工具栏

代码:

<ToolBarTray>
    <ToolBar>
        <Button>
            <StackPanel>
                <Image/>
                <Label/>
            </StackPanel>
        </Button>
        <Button>
            <StackPanel>
                <Image/>
                <Label/>
            </StackPanel>
        </Button>
        <Button>
            <StackPanel>
                <Image/>
                <Label/>
            </StackPanel>
        </Button>
    </ToolBar>
</ToolBarTray>

在图片上我只设置了Source,在标签上我只设置了Content

然而,如图所示,按钮的宽度不同。 "Remove" 按钮比其他按钮宽。

如何才能使所有工具栏按钮与 "Remove" 按钮共享相同的宽度?

这可能会起作用,我还没有测试过,但是通过指定按钮的宽度和图像缩放比例,您应该会发现它可以解决问题。

<Button Width="intValue">
   <StackPanel>
       <Image Source="yourImage" 
              RenderOptions.BitmapScalingMode="Fant" />
       <Label/>
   </StackPanel>
</Button>

您可以同时设置所有按钮的 Width 的一种方法是在 ToolBar.Resources 中使用 Setter,如下所示:

<ToolBar>
  <ToolBar.Resources>
    <Style x:Key="{x:Static ToolBar.ButtonStyleKey}" TargetType="Button">
      <Setter Property="Width" Value="80"/>
    </Style>
  </ToolBar.Resources>
  <Button>
  ...
  <Button>
  ...
</ToolBar>

这样您就不需要在每个 Button 上单独手动设置宽度。

您也可以使用 Setter 来设置 Stretch 属性,像这样:

      <Setter Property="Stretch" Value="None"/>

编辑:

显然,根据 ,您需要确保使用 x:Key="{x:Static ToolBar.ButtonStyleKey}" 设置 Style 才能将其应用于 ToolBar 按钮。我更新了我的答案以反映这一点。