Setting toolbar button sizes using a Style

别等时光非礼了梦想. 提交于 2020-01-21 04:51:06

问题


I have buttons on a toolbar in WPF.

When I do the XAML:

<ToolBar.Resources>
   <Style TargetType="{x:Type Button}">
      <Setter Property="Width" Value="21"></Setter>
      <Setter Property="Height" Value="21"></Setter>
   </Style>
</ToolBar.Resources>

None of the buttons on the toolbar set their sizes accordingly.

I have to go to each button and manually set their widths and heights to the desired values.

Any idea why the Style on the toolbar does not work?


回答1:


This occurs because ToolBar applies the style identified by ToolBar.ButtonStyleKey to buttons, instead of leaving them with the default style. (That's why buttons in Toolbars are flat even though the default style is raised.) You need to "hijack" this style, instead of the default style:

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

Note the x:Key in the Style declaration.




回答2:


If you are adding hardcoded buttons to your toolbar, you can set ToolBar.ItemContainerStyle to a custom style to get the effect you want.

<ToolBar.ItemContainerStyle>
    <Style
        TargetType="Button">
        <Setter
            Property="Width"
            Value="21" />
        <Setter
            Property="Height"
            Value="21" />
    </Style>
</ToolBar.ItemContainerStyle>

If you are using ToolBar.ItemsSource you can instead use ToolBar.ItemTemplate to define a template for your toolbar data.

<ToolBar.ItemTemplate>
    <DataTemplate>
        <Button
            Width="21"
            Height="21"
            Content="{Binding}" />
    </DataTemplate>
</ToolBar.ItemTemplate>

Note that in some cases, both of these can be used at the same time for additional flexibility.

This applies not only to toolbar, but to all derivatives of ItemsControl.

Best of luck,



来源:https://stackoverflow.com/questions/2406079/setting-toolbar-button-sizes-using-a-style

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!