WPF Toolbar Items HorizontalAligment="Right"
I realize this is an old topic, but it still pops up when asking the question. This is how I handle this question:
<Grid>
<Grid.RowDefinitions>
<RowDefinition x:Name="MenuRow" Height="25"/>
<RowDefinition x:Name="ToolbarRow" Height="25"/>
<RowDefinition x:Name="CatalogRow" Height="*"/>
<RowDefinition x:Name="RecipeRow" Height="0.4*"/>
</Grid.RowDefinitions>
<ToolBar Grid.Row="1">
<Button x:Name="tbFileOpen" Margin="0,0,0,0" Click="MenuItem_Click"><Image Source="Icons/Main/File/Load.png"/></Button>
<Button x:Name="tbFileSave" Margin="0,0,0,0" Click="MenuItem_Click"><Image Source="Icons/Main/File/Save.png"/></Button>
<Button x:Name="tbFileClear" Margin="0,0,0,0" Click="MenuItem_Click"><Image Source="Icons/Main/File/New document.png"/></Button>
</ToolBar>
<ToolBar Grid.Row="1" HorizontalAlignment="Right">
<Button x:Name="tbFileExit" Margin="0,0,0,0" Click="MenuItem_Click"><Image Source="Icons/Main/File/Exit.png"/></Button>
</ToolBar>
</Grid>
Effectively: I create two toolbar objects and have them on the same Grid.row. The first one has default (left) alignment, the second one is right aligned. It seems to do the trick for me.
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.