Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

xaml - WPF Toolbar Items HorizontalAligment="Right"

Is it possible to make the elements within a WPF toolbar have a HorizontalAlignment of Right?

<ToolBar Height="38" VerticalAlignment="Top" Grid.Row="1">
    <Button HorizontalAlignment="Left" Width="50" VerticalAlignment="Stretch"/>
    <Button HorizontalAlignment="Left" Width="50" VerticalAlignment="Stretch"/>
    <ComboBox Width="120" HorizontalAlignment="Right"/>
</ToolBar>

I've tried adding the elements inside into a Grid and assigning the ColumnDefinitions to Left/Right as well. I have also tried a StackPanel. No matter what I try I can't seem to get the ComboBox to be "anchored" on the right side of the Toolbar.

UPDATE:

<DockPanel LastChildFill="True">

Doesn't work, It will not fill the ToolBar element like it would a normal element.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Further investigation showed that in order to do this I need to set the width of a Grid within the ToolBar, or as Chris Nicol said, a DockPanel within the ToolBar dynamically to that of the width of the Toolbar using RelativeSource.

However, that did not feel like a clean solution. It is quite complicated to get the Toolbar to update correctly on resizing. So instead I found somewhat of a hack that looks, and operates cleaner by adding an external Grid.

<Grid>
    <ToolBar Height="38" VerticalAlignment="Top" Grid.Row="1">
        <Button HorizontalAlignment="Left" Width="50" VerticalAlignment="Stretch"/>
        <Button HorizontalAlignment="Left" Width="50" VerticalAlignment="Stretch"/>
    </ToolBar>
    
    <ComboBox Margin="0,0,15,0" Width="120" HorizontalAlignment="Right" Grid.Row="1"/>
</Grid>

Since all of my elements are on a Grid, I can place my ComboBox on top of the ToolBar by assigning it's Grid.Row to the same row as the toolbar. After setting my Margins to pull the ComboBox over slightly as not to interfere with looks, it operates as needed with no bugs. Since the only other way I found to do this was setting a DockPanel/Grid's Width property dynamically, I actually feel like this is the cleaner more efficient way to do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...