WPF限制扩展器的大小

时间:2010-12-05 19:37:51

标签: wpf resize height expander

我在扩展器中有多个树视图,它可以随着内容一起增长。但是当高度大于窗户的大小时,它会越过窗户。

显而易见的解决方案是设置Treeview的MaxHeight,但我无法轻易确定,因为可用高度取决于

  • 窗口高度
  • 其他扩展器(打开/关闭)

我需要更改什么才能使树视图的高度自动增长,但不会超过窗口的高度?

<StackPanel CanVerticallyScroll="True" ClipToBounds="False" Height="Auto" Name="StackPanel2" Width="250" DockPanel.Dock="Left" Orientation="Vertical" VerticalAlignment="Top" CanHorizontallyScroll="False" Margin="5">
    <Border BorderThickness="0" CornerRadius="5" Padding="1" BorderBrush="Red" Margin="0,5" >
        <Expander Header="Expander3" Height="Auto" IsExpanded="False" Width="Auto" Margin="2" BorderThickness="1">
           <Grid  Height="Auto" Width="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" >

            <TreeView Height="Auto" BorderThickness="1" Margin="0,0,0,0" Padding="7" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" >
           </TreeView>

        </Grid>
    </Expander>
    </Border>
</StackPanel>

1 个答案:

答案 0 :(得分:2)

我能想到的一种方法是将StackPanel放在ScrollViewer中。这样就可以确保它永远不会超出窗口的高度。你不会为每个扩展器获得一个单独的Scroll(如果它们在同一个StackPanel中?)但是我不能100%确定你在这之后是什么。

<ScrollViewer Name="stackPanelScrollViewer"
              Loaded="stackPanelScrollViewer_Loaded"
              VerticalScrollBarVisibility="Auto">
    <StackPanel CanVerticallyScroll="True" ClipToBounds="False" Height="Auto" Name="StackPanel2" Width="250" DockPanel.Dock="Left" Orientation="Vertical" VerticalAlignment="Top" CanHorizontallyScroll="False" Margin="5">
        <Border BorderThickness="0" CornerRadius="5" Padding="1" BorderBrush="Red" Margin="0,5" >
            <Expander Header="Expander3" Height="Auto" IsExpanded="False" Width="Auto" Margin="2" BorderThickness="1">
                <Grid  Height="Auto" Width="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" >
                    <TreeView Name="treeView1" Height="Auto" BorderThickness="1" Margin="0,0,0,0" Padding="7" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" >
                    </TreeView>
                </Grid>
            </Expander>
        </Border>
    </StackPanel>
</ScrollViewer>

这样做的缺点是TreeView在其ControlTemplate中定义了自己的ScrollViewer,因此如果鼠标位于TreeView上,您将无法使用MouseWheel进行滚动。解决此问题的方法是为每个TreeView附加一个MouseWheel事件处理程序并从那里创建Scroll

private void stackPanelScrollViewer_Loaded(object sender, RoutedEventArgs e)
{
    treeView1.AddHandler(MouseWheelEvent, new RoutedEventHandler(StackPanelMouseWheel), true);
    //treeView2.AddHandler(MouseWheelEvent, new RoutedEventHandler(StackPanelMouseWheel), true);
}
private void StackPanelMouseWheel(object sender, RoutedEventArgs e)
{
    MouseWheelEventArgs eargs = (MouseWheelEventArgs)e;
    double x = (double)eargs.Delta;
    double y = stackPanelScrollViewer.VerticalOffset;
    stackPanelScrollViewer.ScrollToVerticalOffset(y - x);
}