Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toolbar button styles get ignored?

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?

like image 750
TheWommies Avatar asked Mar 09 '10 01:03

TheWommies


2 Answers

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.) Reference.

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.

like image 180
itowlson Avatar answered Sep 21 '22 21:09

itowlson


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,

like image 34
Kep Amun Avatar answered Sep 23 '22 21:09

Kep Amun