Below the sample will save the scroll offset in the virtual machine and load it when the window (TestWindow) opens. You should also store and load the window size, as this will most likely affect the scroll shift. If you want, you can move the code in TestWindow to an attached behavior class.
XAML:
<Window x:Class="ScrollTest.TestWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="TestWindow" Height="200" Width="300" Loaded="OnLoaded" Closing="OnClosing"> <Grid> <ScrollViewer Name="_scroll" VerticalScrollBarVisibility="Auto"> <StackPanel> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> <Button Content="Click me" /> </StackPanel> </ScrollViewer> </Grid> </Window>
Code behind:
using System; using System.ComponentModel; using System.Windows; namespace ScrollTest { public partial class TestWindow : Window { public TestWindow() { InitializeComponent(); } private void OnLoaded(object sender, RoutedEventArgs e) { _scroll.ScrollToVerticalOffset((DataContext as VM).ScrollOffset); } private void OnClosing(object sender, CancelEventArgs e) { (DataContext as VM).ScrollOffset = _scroll.VerticalOffset; } } public class VM { public double ScrollOffset { get; set; } } }
Using:
private void OnOpenOpenTestWindow(object sender, RoutedEventArgs e) { TestWindow testWindow = new TestWindow(); testWindow.DataContext = _vm; testWindow.Show(); } private VM _vm = new VM();
source share