Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an item in a toolbar fill all available space in WPF

I'm trying to make an item on ToolBar (specifically a Label, TextBlock, or a TextBox) That will fill all available horizontal space. I've gotten the ToolBar itself to stretch out by taking it out of its ToolBarTray, but I can't figure out how to make items stretch.

I tried setting Width to Percenatage or Star values, but it doesn't accept that. Setting Horizontal(Content)Alignment to Stretch in various places seems to have no effect either.

like image 629
Cheetah Avatar asked Oct 24 '08 03:10

Cheetah


1 Answers

Unfortunately it looks like the default ControlTemplate for ToolBar doesn't use an ItemsPresenter, it uses a ToolBarPanel, so setting ToolBar.ItemsPanel won't have any effect.

ToolBarPanel inherits from StackPanel. By default its Orientation is bound to the parent ToolBar.Orientation, but you can override this and set its Orientation to Vertical with a Style and this will allow items to stretch horizontally:

<DockPanel>
    <ToolBar DockPanel.Dock="Top">
        <ToolBar.Resources>
            <Style TargetType="{x:Type ToolBarPanel}">
                <Setter Property="Orientation" Value="Vertical"/>
            </Style>
        </ToolBar.Resources>
        <ComboBox HorizontalAlignment="Stretch" SelectedIndex="0">
            <ComboBoxItem>A B C</ComboBoxItem>
            <ComboBoxItem>1 2 3</ComboBoxItem>
            <ComboBoxItem>Do Re Mi</ComboBoxItem>
        </ComboBox>
    </ToolBar>
    <Border Margin="10" BorderBrush="Yellow" BorderThickness="3"/>
</DockPanel>

You can then use a Grid or something in place of the ComboBox above if you want multiple items on a line.

like image 141
Robert Macnee Avatar answered Nov 20 '22 00:11

Robert Macnee