我想在我的程序中使用一个简单的 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>
关于c# - WPF ScrollViewer问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6688942/