tags:

views:

130

answers:

2

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  A: 

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.

itowlson
+1  A: 

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,

omdsmr