Using a TreeView in WPF

Using a tree view in Windows Forms is straightforward, but in WPF the control has undergone a lot of modifications. In this blog I’ll describe how to do some tasks that seem to be easy enough, and describe some caveats.

Scrollbar problem

This is the sample window (Don’t mind the colors, they’re just to show the point):

<Window x:Class=”FindInSvclog.MainWindow”
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
        Title=”MainWindow” Height=”350″ Width=”568″>
    <StackPanel>
        <Canvas Width=”500″ Height=”228″ Name=”searchCanvas”>
        </Canvas>
        <Grid Grid.Row=”1″>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width=”1*”></ColumnDefinition>
                <ColumnDefinition Width=”1*”></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TreeView Background=”#FF00FF00″ Name=”FileTree” AlternationCount=”1″ />
            <GridSplitter Width=”5px” ResizeDirection=”Columns” Background=”DarkSlateGray”/>
            <TextBlock Grid.Column=”1″ Background=”#FF0000FF” />
        </Grid>
    </StackPanel>
</Window>

The highlighted TreeView doesn’t have a vertical scrollbar, even though it should.

The problem isn’t related to the TreeView, but to the StackPanel: In a StackPanel every item gets all the space it needs. So the StackPanel doesn’t report its current size back (this is the correct behavior!). Changing the StackPanel into a Grid solved the problem completely.

Advertisement

About Gaston

MCT, MCSD, MCDBA, MCSE, MS Specialist
This entry was posted in .Net, Development and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s