I am trying to use a simple ScrollViewer in my program, but I’m having a problem.
If I enclose everything in my program in a ScrollViewer, it works fine:
<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>
However, the since the menu is part of the ScrollViewer, the menu scrolls off the screen when the user scrolls down. So I put the ScrollViewer only around the controls under the menu:
<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>
But this time, the ScrollViewer doesn’t work! i.e. even if I resize my window to be smaller than the height required by the labels, the scrollbar does not get activated.
What am I doing wrong?
The problem is caused by your root StackPanel, the StackPanel is not constraining the vertical height of the ScrollViewer.
Try using the DockPanel to position the Menu instead: