我试图获得在Xamarin Forms中的不同视图之间传递数据的基础。
我有一个Meeting类,其中包含一个可观察的集合。在后面的代码中,我还有另一个ObservableCollection
用作ItemSource
的listview
。后面代码中的ObservableCollection
可以正常工作,但是当我尝试设置myMeeting.MeetingInvitees = _myMeetingInvitees
时,我收到此消息:
System.NullReferenceException:对象引用未设置为实例
一个对象
在后面的代码的构造函数中,我有:
myMeeting = this.BindingContext as Meeting;
这不会初始化
myMeeting
吗? Topic和Place属性可以正常工作,但不能正常工作。因此,当我这样做时:myMeeting.MeetingInvitees = _myMeetingInvitees;
这会不会将它们设置为相同的地址?
我觉得在Meeting类中设置
MeetingInvitees
的属性时我不了解一些基本知识谢谢您能指出我正确的方向!
Meeting.cs:
private ObservableCollection<String> meetingInvitees;
private string meetingTopic;
private string meetingPlace;
public ObservableCollection<string> MeetingInvitees
{
get { return meetingInvitees; }
set
{
meetingInvitees = value;
}
}
public string MeetingTopic
{
get { return meetingTopic; }
set
{
meetingTopic = value;
OnPropertyChanged("MeetingTopic");
}
}
public string MeetingPlace
{
get { return meetingPlace; }
set
{
meetingPlace = value;
OnPropertyChanged("MeetingPlace");
}
}
Xamarin代码背后
public Meeting myMeeting;
public ObservableCollection<string> _myMeetingInvitees;
public NewMeetingContactsView ()
{
InitializeComponent ();
_myMeetingInvitees = new ObservableCollection<string>();
myMeeting = this.BindingContext as Meeting;
listAttendees.ItemsSource = _myMeetingAttendess;
}
async void btnNext_Clicked(object sender, EventArgs e)
{
myMeeting.MeetingInvitees = _myMeetingAttendess;
var nextpage = new NewMeetingOverviewView();
nextpage.BindingContext = myMeeting;
await Navigation.PushAsync(nextpage);
}
async void btnCancel_Clicked(object sender, EventArgs e)
{
await Navigation.PopToRootAsync();
}
void btnAdd_Clicked(object sender, EventArgs e)
{
_myMeetingAttendess.Add(entryName.Text);
}
最佳答案
在构造函数中,而不是_myMeetingInvitees = new ObservableCollection<string>();
初始化myMeeting对象后,将其更改为以下代码。
public NewMeetingContactsView ()
{
InitializeComponent ();
myMeeting = new Meeting();
myMeeting.MeetingInvites = new ObservableCollection<string>();
this.BindingContext = myMeeting;
listAttendees.ItemsSource = myMeeting.MeetingInvites;
}
您似乎没有为myMeeting初始化属性MeetingInvites,这就是引发空引用错误的原因。