How to align button on wpf treeview

Hi, I am looking for a way to align the buttons in my tree structure so that it looks in the same column, even if it is at any level. For example:

Item1 [Button] Item2 [Button] Item3[Button] 

I want it to look like

 Item1 [Button] Item2 [Button] Item3 [Button] 

Anyway, can I do it ..?

+7
wpf treeview
source share
1 answer

First, check out this Horizontal Stretch blog post on TreeViewItems . By default, the ControlTemplate for TreeViewItem does not allow you to stretch the contents of the header, which is what you need for this. Use the TreeViewItem style recommended by the author, but change

 <Setter Property="HorizontalContentAlignment" Value="Center" /> 

to

 <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 

You will now have a TreeViewItem where the contents of the header are stretched across the entire width of the TreeViewItem. To force the TreeViewItem to render text and a button, use the ItemTemplate TreeView property. If you want the buttons to be right-aligned, you can use the DockPanel:

 <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding ...}"> <DockPanel LastChildFill="False"> <TextBlock DockPanel.Dock="Left" Text="{Binding ...}"/> <Button DockPanel.Dock="Right" Content="{Binding ...}"/> </DockPanel> </HierarchicalDataTemplate> </TreeView.ItemTemplate> 

If the contents of the buttons can be variable in size and you want them all to be the same width, use a Grid with SharedSizeScope. Set Grid.IsSharedSizeScope="True" in the TreeView, and then in the ItemTemplate do something like this:

 <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding ...}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition SharedSizeGroup="Buttons"/> </Grid.ColumnDefinitions> <TextBlock Text="{Binding ...}"/> <Button Grid.Column="1" Content="{Binding ...}"/> </Grid> </HierarchicalDataTemplate> </TreeView.ItemTemplate> 
+7
source share

All Articles