简体   繁体   English

Windows 8 C#将ScrollerViewer状态保存在Frame.Navigate

[英]Windows 8 C# Save ScrollerViewer state on Frame.Navigate

I need to save the position of my ScrollViewer so that when I navigate to a page and hit the back arrow, it will still be at the position it was. 我需要保存ScrollViewer的位置,以便当我导航到页面并单击后退箭头时,它仍将保持在原来的位置。

I'm using: 我正在使用:

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            base.LoadState(navigationParameter, pageState);
            if (pageState != null && pageState.ContainsKey("ScrollerPosition"))
            {
                mainScrollViewer.ScrollToHorizontalOffset((double) pageState["ScrollerPosition"]);
            }
        }

and

protected override void SaveState(Dictionary<String, Object> pageState)
        {
            base.SaveState(pageState);
            pageState["ScrollerPosition"] = mainScrollViewer.HorizontalOffset;
        }

but it isn't restoring the state it was at. 但这并没有恢复到原来的状态。 What am I doing wrong? 我究竟做错了什么? (I'm very new to Windows 8!) (我是Windows 8的新手!)

The issue might be that LoadState is called prior to any of your data being loaded. 问题可能是在加载任何数据之前先调用LoadState If that is the case, there is no content to scroll so your ScrollToHorizontalOffset call has no effect. 在这种情况下,没有要滚动的内容,因此您的ScrollToHorizontalOffset调用无效。

You don't have any detail on how you load your data, so I cannot make a specific recommendation. 您没有如何加载数据的详细信息,因此我无法提出具体建议。 However, the general solution is to make sure all of your data is loaded prior to your call to set the scroll position. 但是,一般的解决方案是确保在调用设置滚动位置之前调用所有数据。

The place to restore your scroll viewer is in the Loaded event. 恢复滚动查看器的位置在Loaded事件中。 Add a handler in your constructor: 在构造函数中添加一个处理程序:

scrollViewer.Loaded += (sv,event) => ScrollViewerLoaded(sv, event);

(or alternately through the XAML) (或通过XAML替代)

Save out the state as you have in SaveState() . 保存状态,就像在SaveState() Load the value in LoadState() as you have, but instead of using the value immediately cache it until you get to that Loaded event: 将值按原样加载到LoadState()中,但不要立即使用该值对其进行高速缓存,直到到达该Loaded事件为止:

void ScrollViewerLoaded(Object sender, RoutedEventArgs event)
{
    mainScrollViewer.ScrollToHorizontalOffset(cachedScrollPosition);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM