0

当我转到另一个页面时,我试图保留页面状态,但由于某种原因,当我返回此页面时,这些项目将返回到它们的默认状态。为什么它不起作用?它似乎完美地遵循了教程......

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);


        State["Title"] = TitleTextBox.Text;

        //all of those are RadioButtons - if their is a better way to do it then please comment :)
        int i = new int();
        if (RB0.IsChecked.Value)
            i = 0;
        else if (RB1.IsChecked.Value)
            i = 1;
        else if (RB2.IsChecked.Value)
            i = 2;
        else if (RB3.IsChecked.Value)
            i = 3;
        State["CheckedRB"] = i;

    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        if (State.ContainsKey("Title"))
            TitleTextBox.Text = State["Title"] as string;
        if (State.ContainsKey("CheckedRB"))
        {
            int i = (int)State["CheckedRB"];

            if (i == 0)
                RB0.IsChecked = true;
            else if (i == 1)
                RB1.IsChecked = true;
            else if (i == 2)
                RB2.IsChecked = true;
            else if (i == 3)
                RB3.IsChecked = true;
        }
     }

编辑:我通过添加断点来追踪问题。

            protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);


        State["Title"] = TitleTextBox.Text;
        string look0 = WorkOutName.Text; 
        string look = State["WorkOutName"] as string; 

        int i = new int();
        if (RB0.IsChecked.Value)
            i = 0;
        else if (RB1.IsChecked.Value)
            i = 1;
        else if (RB2.IsChecked.Value)
            i = 2;
        else if (RB3.IsChecked.Value)
            i = 3;
        State["CheckedRB"] = i;   <-------- breakpoint

结果如下:

(OnNavigatedFrom)
look0 : "Text From TextBox"
look1 : "Text From TextBox"
i : (0, 1, 2, or 3)

与 OnNavigatedTo 相同:

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        if (State.ContainsKey("Title"))
            TitleTextBox.Text = State["Title"] as string; <--breakpoint
        if (State.ContainsKey("CheckedRB"))
        {
            int i = (int)State["CheckedRB"]; <--breakpoint

            if (i == 0)
                RB0.IsChecked = true;
            else if (i == 1)
                RB1.IsChecked = true;
            else if (i == 2)
                RB2.IsChecked = true;
            else if (i == 3)
                RB3.IsChecked = true;
        }
     }

并且它们中的任何一个(在 OnNavigatedTo 上)都没有熄灭。

4

1 回答 1

1

我试过你的代码,它似乎工作正常。我不知道这是否是您的情况,但请记住,如果您在应用程序中有以下导航流程:

Page1 (forward navigation)-> Page2 (back navigation)-> Page1 (forward navigation)-> Page2

如果您在第一次访问时将状态保存在 Page2 中,再次返回 Page2 时将不会保留该状态,这是因为在进行后退导航时该页面被丢弃,该页面的状态字典也是如此。您可以在文档中阅读更多相关信息。

于 2012-07-02T17:28:10.107 回答