When I pass an Exam
object to this viewmodel constructor, both WriteLine
calls behave as expected, indicating that exam
(and Exam
) is not null.
(I put the WriteLine
s in because I was trying to bind to {Binding Exam.Name}
in my view and nothing )was coming in.
public ExamInfoViewModel(Exam exam, RelayCommand startAcquisitionHandler, RelayCommand startEditHandler, RelayCommand backHandler)
{
base.DisplayName = "Exam Info";
Exam = exam;
System.Console.WriteLine(Exam);
System.Console.WriteLine(Exam.Name);
StartAcquisitionCommand = startAcquisitionHandler;
StartEditingCommand = startEditHandler;
BackCommand = backHandler;
}
However, I get an error, highlighting the second WriteLine
call.
System.NullReferenceException: 'Object reference not set to an instance of an object.' Gui.ViewModels.ViewModelWithExam.Exam.get returned null.
The other arguments to the constructor work, by the way. If I take out the WriteLine
calls I don't get any errors, and the commands work as expected (well I've only actually implemented the BackCommand
in my view, but that one works).
The code that calls the constructor:
private RelayCommand OnSelectExam => new RelayCommand(exam =>
{
Exam = (Exam)exam;
CurrentViewModel = new ExamInfoViewModel(
Exam,
OnRequestAcquireImages,
OnRequestEditExam,
new RelayCommand(_ => GoHome())
);
});
And here's the base class:
public class ViewModelWithExam : ViewModelBase
{
private Exam _exam;
public Exam Exam
{
get => _exam;
set
{
_exam = value;
OnPropertyChanged();
}
}
}
UPDATE:
I put some console writers after the first line in OnSelectExam
, and it turns out it runs twice, once with exam
non-null, and then with it null. This appears to be what the actual problem is. I imagine the code from ExamsIndexViewModel
, which calls OnSelectExam
, will help:
internal class ExamsIndexViewModel : NavigableViewModel
{
public ExamsIndexViewModel(RelayCommand newExamHandler, RelayCommand selectExamHander)
{
base.DisplayName = "Select Exam";
NewExamCommand = newExamHandler;
SelectExamCommand = selectExamHander;
ExamsList = GetExams();
}
public RelayCommand NewExamCommand
{
get;
}
public RelayCommand SelectExamCommand
{
get;
}
And from the class that instantiates the ExamsIndexViewModel
:
private void GoHome()
{
CurrentViewModel = new ExamsIndexViewModel(OnNewExam, OnSelectExam);
}
public ExamsTabViewModel() : base()
{
base.DisplayName = "Exams";
GoHome();
}