C# 通过导航页面传递参数时引用为空[WP8.1]
我不明白为什么我做错了,或者我做错了什么,但是当在我的Windows Phone 8.1应用程序中执行以下代码时,我得到了一个空引用异常: 首先,应用程序导航并将所选电台传递到下一页 主页上的代码:C# 通过导航页面传递参数时引用为空[WP8.1],c#,xaml,navigation,nullreferenceexception,windows-phone-8.1,C#,Xaml,Navigation,Nullreferenceexception,Windows Phone 8.1,我不明白为什么我做错了,或者我做错了什么,但是当在我的Windows Phone 8.1应用程序中执行以下代码时,我得到了一个空引用异常: 首先,应用程序导航并将所选电台传递到下一页 主页上的代码: // When an item is selected, go to the next page and pass info private void listBoxStations_SelectionChanged(object sender, SelectionChangedEv
// 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
}
当我尝试将txtstationfile.Text更改为station.StationName时,特别发生了此错误
如果我取出更改文本框的代码,并逐步执行该程序,则表明在OnNavigatedTo方法结束时station变量实际上不是null
任何帮助都将不胜感激
-Johan似乎不是电台是空的,而是
this.txtStationTitle
您在on navigatedto
中执行所有操作,而包括您尝试更改的文本块在内的页面(XAML)未完全加载,因此文本块为null,当您尝试执行this.txtStationTitle.Text
时,您会得到null引用异常
但是,如果在页面的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.txtStationTitle
和station
将非常容易找到空值