Customize toolbar button sizes with style

I have toolbar buttons in WPF.

When I do 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 sets the appropriate dimensions.

I need to go to each button and manually set their width and height to the desired values.

Any idea why the style on the toolbar is not working?

+6
styles wpf toolbar
source share
2 answers

This is because the ToolBar applies the style denoted by ToolBar.ButtonStyleKey to the buttons, instead of leaving them by default. (This is why the buttons on the toolbars are flat, although the default style is enhanced.) You need to β€œcapture” 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.

+8
source share

If you add hard-coded buttons to your toolbar, you can set ToolBar.ItemContainerStyle to a custom style to get the desired effect.

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

If you use ToolBar.ItemsSource, you can instead use ToolBar.ItemTemplate to define a template for the data in your toolbar.

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

Please note that in some cases both of them can be used simultaneously for added flexibility.

This applies not only to the toolbar, but also to all derived ItemsControl.

Good luck,

+2
source share

All Articles