如何恢复FlipView的selectedIndex

时间:2015-03-12 17:11:52

标签: c# windows xaml windows-phone-8.1 windows-8.1

我正在尝试实现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));
}

...

在xaml中我定义了以下FlipView:

<FlipView x:Name="MyFlipView" Grid.Row="2" ItemsSource="{Binding Items}">
    <FlipView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"></TextBlock>
        </DataTemplate>
    </FlipView.ItemTemplate>
</FlipView>

现在我想在离开时保存页面的状态(保存项目和当前位置)

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"];
    }
}

当我尝试恢复SelectedIndex时,应用程序崩溃为Value does not fall within the expected range

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

0 个答案:

没有答案