WPF ScrollViewer problem
本文关键字:problem ScrollViewer WPF | 更新日期: 2023-09-27 18:02:16
我想在我的程序中使用一个简单的ScrollViewer,但是我遇到了一个问题。
如果我将程序中的所有内容都包含在ScrollViewer中,它可以正常工作:
<Window x:Class="WpfTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Name="PrimaryWindow">
<ScrollViewer>
<StackPanel>
<Menu Height="21" VerticalAlignment="Top">
<MenuItem Header="File"/>
<MenuItem Header="Edit"/>
</Menu>
<StackPanel>
<TextBlock Text="1"/>
<TextBlock Text="2"/>
<TextBlock Text="3"/>
<TextBlock Text="4"/>
<TextBlock Text="5"/>
<TextBlock Text="6"/>
<TextBlock Text="7"/>
<TextBlock Text="8"/>
<TextBlock Text="9"/>
<TextBlock Text="10"/>
</StackPanel>
</StackPanel>
</ScrollViewer>
</Window>
但是,由于菜单是ScrollViewer的一部分,因此当用户向下滚动时,菜单会从屏幕上滚动出去。所以我把ScrollViewer只放在菜单下的控件周围:
<Window x:Class="WpfTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Name="PrimaryWindow">
<StackPanel>
<Menu Height="21" VerticalAlignment="Top">
<MenuItem Header="File"/>
<MenuItem Header="Edit"/>
</Menu>
<ScrollViewer>
<StackPanel>
<TextBlock Text="1"/>
<TextBlock Text="2"/>
<TextBlock Text="3"/>
<TextBlock Text="4"/>
<TextBlock Text="5"/>
<TextBlock Text="6"/>
<TextBlock Text="7"/>
<TextBlock Text="8"/>
<TextBlock Text="9"/>
<TextBlock Text="10"/>
</StackPanel>
</ScrollViewer>
</StackPanel>
</Window>
但这一次,ScrollViewer不工作!也就是说,即使我将窗口的大小调整为小于标签所要求的高度,滚动条也不会被激活。
我做错了什么?
这个问题是由你的根StackPanel引起的,StackPanel没有限制ScrollViewer的垂直高度。
尝试使用DockPanel来定位菜单:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<DockPanel>
<Menu DockPanel.Dock="Top" Height="21" VerticalAlignment="Top">
<MenuItem Header="File"/>
<MenuItem Header="Edit"/>
</Menu>
<ScrollViewer>
<StackPanel>
<TextBlock Text="1"/>
<TextBlock Text="2"/>
<TextBlock Text="3"/>
<TextBlock Text="4"/>
<TextBlock Text="5"/>
<TextBlock Text="6"/>
<TextBlock Text="7"/>
<TextBlock Text="8"/>
<TextBlock Text="9"/>
<TextBlock Text="10"/>
</StackPanel>
</ScrollViewer>
</DockPanel>
ScrollViewer将显示它的条形条,只有当祖先元素的高度或宽度改变时。所以,你的祖先是StackPanel,当你调整窗口大小时,它不会改变大小。
永远不要在StackPanel中使用ScrollViewer,因为StackPanel和它的内容一样大!所以ScrollViewer认为它总是有足够的位置!
scrollViewer必须位于所有