NavigateTo() 函数在构造函数之前被调用? [英] NavigateTo() Function is being called before constructor?

查看:31
本文介绍了NavigateTo() 函数在构造函数之前被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Windows 手机应用程序,在我的 MainPage.xaml.cs 文件中,我有一个私有成员正在重写方法 OnNavigateTo() 中进行更改.尽管它的值发生了变化,但在 MainPage 构造函数中,它的值重置为 0(它是一个 int 成员).我猜 OnNavigateTo() 方法在构造函数之前被调用,但如果是这样,我会有一个 nullReferenceException.什么会导致这个问题?

I am developing a Windows phone App and in my MainPage.xaml.cs file I have one private member that is being changed in the overrided method OnNavigateTo(). Although its value is changed, after that in the MainPage constructor its value resets to 0 (It's an int member). I guess that OnNavigateTo() method is being called BEFORE the constructor but if so I would have a nullReferenceException. What can cause that problem?

OnNavigateTo() 函数:

The OnNavigateTo() Function:

if (NavigationContext.QueryString.ContainsKey("leftDuration")){

if (NavigationContext.QueryString.ContainsKey("leftDuration")) {

            //Get the selected value from IntroductionPage as a string
            var leftRecievedInformation = NavigationContext.QueryString["leftDuration"];

            //Convert the string to an enum object
            var firstRunLeftChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), leftRecievedInformation);

            //Set the leftDuration value to the model object               
            _firstRunLeftDuration = getDurationAsNumber(firstRunLeftChosenDuration);

            MessageBox.Show(_firstRunLeftDuration + "");
            model.Left.LifeTime = _firstRunLeftDuration;

        }

我有问题的成员是 _firstRunLeftDuration 值.虽然,如您所见,我设置了 model.Left.LifeTime 值,但在 MainPage.xaml 中我仍然得到默认的 0 值……就像完全忽略了这行代码一样.我知道代码不是特别清楚,但我认为添加额外的无用代码行没有好处.

My problematic member is the _firstRunLeftDuration value. Although, as you can see, i set the model.Left.LifeTime value, in the MainPage.xaml I still get the default 0 value... It' like completely ignoring this line of code.. I know the code is not particularly clear but I don't think its beneficial to add extra lines of useless code.

这是 MainPage.xaml.cs 文件:公共部分类 MainPage : PhoneApplicationPage{

Here's the MainPage.xaml.cs file: public partial class MainPage : PhoneApplicationPage {

    public ContactLensesModel model;
    private int _firstRunLeftDuration, _firstRunRightDuration; //Members used for the initialization of the app

    public int FirstRunLeftDuration
    {
        get
        {
            return _firstRunLeftDuration;
        }
        set
        {
            _firstRunLeftDuration = value;
        }
    }

    public int FirstRunRightDuration
    {
        get
        {
            return _firstRunRightDuration;
        }
        set
        {
            _firstRunRightDuration = value;
        }

    }

    public ContactLensesModel Model
    {
        get
        {
            return model;
        }
        set
        {
            model = value;
        }

    }

    // Constructor
    public MainPage()
    {

        InitializeComponent();

        // Sample code to localize the ApplicationBar
        BuildLocalizedApplicationBar();

        //Should check if the user starts the app for the first time....

        //Create a new model
        Model = new ContactLensesModel();
        Model.setLeftNewStartingDate();
        Model.setRightNewStartingDate();


        //Should load the already saved model if the user in not entering for the first time...
        //....
        //....

        loadModel();

        //Connect the data Context
        leftLensDaysRemaining.DataContext = Model.Left;
        rightLensDaysRemaining.DataContext = Model.Right;


    }

    private int getDurationAsNumber(LensLifetime duration)
    {

        if (duration.Equals(LensLifetime.Day))
            return 1;
        else if (duration.Equals(LensLifetime.Two_Weeks))
            return 14;
        else
            return DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        //Get the arguments as strings and convert them to an enum, is true only when the user enters app for the first time.
        if (NavigationContext.QueryString.ContainsKey("leftDuration"))
        {

            //Get the selected value from IntroductionPage as a string
            var leftRecievedInformation = NavigationContext.QueryString["leftDuration"];

            //Convert the string to an enum object
            var firstRunLeftChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), leftRecievedInformation);

            //Set the leftDuration value to the model object        

            FirstRunLeftDuration = getDurationAsNumber(firstRunLeftChosenDuration);
            Model.Left.LifeTime = FirstRunLeftDuration;

        }
        if (NavigationContext.QueryString.ContainsKey("rightDuration"))
        {

            //Get the selected value from IntroductionPage as a string
            var rightRecievedInformation = NavigationContext.QueryString["rightDuration"];

            //Convert the string to an enum object
            var firstRunRightChosenDuration = (LensLifetime)Enum.Parse(typeof(LensLifetime), rightRecievedInformation);

            //Set the leftDuration value to the model object
            _firstRunRightDuration = getDurationAsNumber(firstRunRightChosenDuration);
            Model.Right.LifeTime = _firstRunRightDuration;
        }


    }

    /// <summary>
    /// Loads the model from the isolated Storage
    /// </summary>
    private void loadModel()
    {
         //Load the model...
    }


    private void BuildLocalizedApplicationBar()
    {
        // Set the page's ApplicationBar to a new instance of ApplicationBar.
        ApplicationBar = new ApplicationBar();

        // Create a new button and set the text value to the localized string from AppResources.
        ApplicationBarIconButton appBarSettingsButton = new ApplicationBarIconButton(new Uri("/Assets/Icons/settingsIcon4.png", UriKind.Relative));
        appBarSettingsButton.Text = AppResources.AppBarSettingsButtonText;
        appBarSettingsButton.Click += appBarButton_Click;
        ApplicationBar.Buttons.Add(appBarSettingsButton);

        // Create a new menu item with the localized string from AppResources.
        //ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //ApplicationBar.MenuItems.Add(appBarMenuItem);
    }

    void appBarButton_Click(object sender, EventArgs e)
    {
        NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.RelativeOrAbsolute));
    }

    private void leftButtonChange_Click(object sender, RoutedEventArgs e)
    {
        model.setLeftNewStartingDate();
    }

    private void rightChangeButton_Click(object sender, RoutedEventArgs e)
    {
        model.setRightNewStartingDate();
    }
}

}

推荐答案

OnNavigatedTo 方法不能在构造函数之前调用.构造函数总是首先执行.我认为您的 model.Left.LifeTime 不会引发 PropertyChanged 事件.因此,您的 View 不会知道您给它一个值.因此它会显示 model.Left.Lifetime 的默认值,可能是 0.

The OnNavigatedTo method cannot be called before the constructor. The constructor is always executed first. I think your model.Left.LifeTime doesn't raise a PropertyChanged event. Hence, your View won't know you are giving it a value. Therefore it will show the default value of model.Left.Lifetime which is probably 0.

另一方面,如果不查看其余代码,就很难判断.

On the other hand, it's hard to tell without seeing the rest of your code.

这篇关于NavigateTo() 函数在构造函数之前被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆