简体   繁体   中英

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.

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.

尝试在ToolBar中放置一个水平StackPanel,然后在StackPanel中放置您想要的元素。

You need a special custom panel like auto stretched stack panel , and replace the toolbarpanel. Check this out you can find one panel there http://blendables.com/products/productsLayoutmix.aspx

您是否尝试将项目包装在网格中,而不是在StackPanel中?

I've had this same problem for a while, and there is very little help available online.

Since it doesn't sound like you need all the extra functionality of a Toolbar (collapsible/movable trays), why not just use a Top-docked Grid, and tweak the background a little to make it look like a standard toolbar?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM