1
votes

I have a problem that when TreeView is placed inside a container that has ScrollViewer, the TreeView's scrollbars doesn't work, instead the container's ScrollViewer's contents are resized so that all TreeView items are visible.

In WinForms I could just set the container's minimum content width and height, but how to achieve this in WPF?

Here's the example XAML:

<Window x:Class="TestWpfTreeViewInsideScrollViewer.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ScrollViewer Name="scroll1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" >
        <Grid MinHeight="230" MinWidth="200" Grid.IsSharedSizeScope="True">
            <Button Content="Button" Width="74" Height="52" Margin="10,24,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"/>
            <Button Content="Button" Height="52" Margin="89,24,10,0" VerticalAlignment="Top"/>
            <Button Content="Button" Width="74" Height="52" Margin="10,81,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"/>

            <TreeView Margin="10,138,10,55">
                <TreeViewItem IsExpanded="True" Header="This is a long text but the treeview is not scrolling">
                    Instead the TreeView is expanding its size to fit all these nodes inside it, i want that the upper scroller take in only when grid minwidth 200 is reached, not before
                    <TreeViewItem IsExpanded="True" Header="This is a long text but the treeview is not scrolling">This is a long text but the treeview is not scrolling
                    </TreeViewItem>
                </TreeViewItem>
                <TreeViewItem IsExpanded="True" Header="This is a long text but the treeview is not scrolling">This is a long text but the treeview is not scrolling</TreeViewItem>
                <TreeViewItem IsExpanded="True" Header="This is a long text but the treeview is not scrolling">This is a long text but the treeview is not scrolling</TreeViewItem>
            </TreeView>

            <Button Content="Button" Margin="10,0,10,10" Height="40" VerticalAlignment="Bottom"/>
        </Grid>
    </ScrollViewer>

</Grid>

1

1 Answers

5
votes

Scrollviewer has an undefined space for its contents.

This would mean that the TreeView was displayed in a size in which it does not need to display its ScrollViewer.

At least the Width and Height of the TreeView inside the ScrollViewer should be defined.

UPDATE:

If you want to make the Treeview Width resize dynamically, you need to use data binding.

<TreeView Margin="10,138,10,55" Width="{Binding ElementName=scroll1, Path=ActualWidth}">

You can also bind Width to other controls if ScrollViewer does not satisfy the Treeview Width.

I hope this helps.