繁体   English   中英

通过导航页面传递参数时为Null参考[WP8.1]

[英]Null Reference when Passing Parameter with Navigating Pages [WP8.1]

我不明白为什么或做错了什么,但是在Windows Phone 8.1应用程序中执行以下代码时,我得到了一个空引用异常:

首先,应用程序导航并将selectedStation传递到下一页...

来自主页的代码:

    // When an item is selected, go to the next page and pass info
    private void listBoxStations_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // Get the selected station item
        CompleteStation selectedStation = (CompleteStation)this.listBoxStations.SelectedItem;

        this.Frame.Navigate(typeof(StationInformationPage), selectedStation);


        // Make sure we set the selected index to -1 after item is selected so
        // when we come back to page, no items are selected
        this.listBoxStations.SelectedIndex = -1;
    }

这是在下一页中获取空错误的代码:

    private CompleteStation station;

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        this.navigationHelper.OnNavigatedTo(e);
        this.station = (CompleteStation)e.Parameter;
        AddInformation();
    }

    private void AddInformation()
    {
        this.txtStationTitle.Text = station.StationName;
        // Add more information here
    }

当我尝试将txtStationTile.Text更改为station.StationName时,该错误特别发生。

如果我取出更改文本框的代码,然后逐步执行该程序,则表明在OnNavigatedTo方法的末尾,station变量实际上并不为空。

任何帮助将不胜感激!

-Johan

似乎不是工作站为空,而是this.txtStationTitle

您正在用OnNavigatedTo进行所有操作, OnNavigatedTo完全加载包括您要更改的TextBlock的页面(XAML),因此TextBlock为null,当您尝试执行this.txtStationTitle.Text ,您会得到NullReferenceException。

但是,如果您在Page的Loaded事件处理程序中调用AddInformation ,则可以确保页面已完全加载,并且TextBlock不再为null。

public SomePage()
{
    this.InitializeComponent();
    this.Loaded += SomePage_Loaded;
}

void SomePage_Loaded(object sender, RoutedEventArgs e)
{
    AddInformation();
}

这种类型的异常通常很容易调试。 在以下行上放置一个断点:

this.txtStationTitle.Text = station.StationName;

并检查this.txtStationTitlestation可以非常轻松地找出确切为null的内容。

暂无
暂无

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

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