开发者

How can I vertically align the bullet in a XAML TreeView HierarchicalDataTemplate?

When a node in my TreeView has multiple lines, the TreeView bullet gets vertically centered.

How can I top-align the TreeView bullet?

alt text http://www.deviantsart.com/upload/1uh2k8p.png

<pages:BasePage.Resources>
    <data:HierarchicalDataTemplate x:Key="OutlineTemplate"
        ItemsSource="{Binding OutlineDocumentObjects}">
        <TextBlock Text="{Binding Line}" 
            TextWrapping="Wrap" 
            VerticalAlignment="Top"
            Width="600"/>
    </data:HierarchicalDataTemplate>
</pages:BasePage.Resources>

<StackPanel Style="{StaticResource StackPanelPageWrapperStyle}">
    <tk:TreeView x:Name="TheTr开发者_Python百科eeView" 
        ItemsSource="{Binding TheOutline.OutlineDocumentObjects}"
        ItemTemplate="{StaticResource OutlineTemplate}">
    </tk:TreeView>
</StackPanel>


Good question... of course, it could be done by redefining the template, but it's a pain... (if you want to go that way, extract the template with StyleSnooper or ShowMeTheTemplate and change the VerticalAlignment of the ToggleButton)

Another way is to inherit TreeViewItem and override the OnApply method. Since the ToggleButton has a name ("Expander") in the default template, you can find it and apply the VerticalAlignment you want :

public class TopAlignedTreeViewItem : TreeViewItem
{
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        if (Template != null)
        {
            ToggleButton btn = Template.FindName("Expander", this) as ToggleButton;
            if (btn != null)
            {
                btn.VerticalAlignment = VerticalAlignment.Top;
            }
        }
    }
}

For the TreeView to generate TopAlignedTreeViewItems instead of TreeViewItems, you also need to make your own TreeView :

public class TopAlignedTreeView : TreeView
{
    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return (item is TopAlignedTreeViewItem);
    }

    protected override System.Windows.DependencyObject GetContainerForItemOverride()
    {
        return new TopAlignedTreeViewItem();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜