Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何恢复FlipView的selectedIndex_C#_Windows_Xaml_Windows Phone 8.1_Windows 8.1 - Fatal编程技术网

C# 如何恢复FlipView的selectedIndex

C# 如何恢复FlipView的selectedIndex,c#,windows,xaml,windows-phone-8.1,windows-8.1,C#,Windows,Xaml,Windows Phone 8.1,Windows 8.1,我正在尝试实现flipview的保存和恢复状态。为了解释这个问题,我简化了这个例子: 我从UI中的两个按钮开始,一个向ObservableCollection添加新项目,另一个导航到另一个页面: private ObservableCollection<String> items = new ObservableCollection<String>(); public TestPage() { this.InitializeComponent(); t

我正在尝试实现flipview的保存和恢复状态。为了解释这个问题,我简化了这个例子:

我从UI中的两个按钮开始,一个向ObservableCollection添加新项目,另一个导航到另一个页面:

private ObservableCollection<String> items = new ObservableCollection<String>();

public TestPage()
{
    this.InitializeComponent();

    this.navigationHelper = new NavigationHelper(this);
    this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
    this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
    DefaultViewModel["Items"] = items;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    items.Add("Test " + DateTime.Now.ToString("HH:mm:ss tt"));
}

private void Button_Click_Page2(object sender, RoutedEventArgs e)
{
    Frame.Navigate(typeof(Page2));
}

...
然后(问题来了)在我返回页面时将其还原:

private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
    if (e.PageState != null)
    {
        DefaultViewModel["Items"] = e.PageState["Items"];
        /*CRASHES*/ MyFlipView.SelectedIndex = (int)e.PageState["Selected"];
    }
}
当我尝试还原SelectedIndex时,应用程序崩溃,其
值不在预期范围内


我认为这是因为此时FlipView尚未加载已恢复的项目。如何解决此问题?

我不确定(我没有尝试过),但您可以在NavigationHelper\u LoadState中将选定的值存储到变量中,并在加载后设置FlipView的索引。谢谢。我如何确切地知道它是何时加载的?请在加载的事件句柄中执行此操作。请尝试在页面中加载。加载的事件或FlipView。加载的事件。您也可以尝试使用FlipView.Items.VectorChanged事件,因为我认为一旦Items属性发生更改,就应该触发它,这可能适合设置FlipView的索引。我现在不太确定首先会发生什么-LoadState事件或Loaded,因此需要尝试一些事情。
private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
    e.PageState["Items"] = items;
    e.PageState["Selected"] = MyFlipView.SelectedIndex;
}
private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
    if (e.PageState != null)
    {
        DefaultViewModel["Items"] = e.PageState["Items"];
        /*CRASHES*/ MyFlipView.SelectedIndex = (int)e.PageState["Selected"];
    }
}