当放置在另一个ScrollViewer中时,WPF TreeView不显示滚动条

时间:2014-01-09 07:45:46

标签: wpf treeview scrollviewer

我遇到的问题是,当TreeView放置在具有ScrollViewer的容器内时,TreeView的滚动条不起作用,而是调整容器的ScrollViewer内容的大小,以便所有TreeView项都可见。

在WinForms中,我可以设置容器的最小内容宽度和高度,但是如何在WPF中实现这一点?

以下是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 个答案:

答案 0 :(得分:5)

Scrollviewer的内容空间未定义。

这意味着TreeView的显示大小不需要显示其ScrollViewer。

至少应定义ScrollViewer中TreeView的宽度和高度。

更新:

如果要动态调整树视图宽度,则需要使用数据绑定。

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

如果ScrollViewer不满足Treeview Width,您还可以将Width绑定到其他控件。

我希望这会有所帮助。