开发者

How to align button on wpf treeview

开发者 https://www.devze.com 2023-01-12 01:45 出处:网络
Hi i am looking for a way to align the buttons in my treeview so that it will look l开发者_StackOverflow中文版ike in the same column even if it is in any level.

Hi i am looking for a way to align the buttons in my treeview so that it will look l开发者_StackOverflow中文版ike in the same column even if it is in any level. Eg:

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

i want it to look like

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

Any way that i can do this..?


First, take a look at this blog entry Horizontal stretch on TreeViewItems. The default ControlTemplate for TreeViewItem does not allow the header content to stretch, which you will need it to do. Use the TreeViewItem Style that the author recommends, but change

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

to

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

Now you will have a TreeViewItem where the header content stretches across the entire width of the TreeViewItem. To get the TreeViewItem to render with text plus a button, use the ItemTemplate property of the TreeView. If you just want the buttons right-aligned, you could use a 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 may have variable size and you want them all to have the same width, use a Grid with SharedSizeScope. Set Grid.IsSharedSizeScope="True" in the TreeView and then in your 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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号