I am using WPF with the Prism framework. I have tried to implement loading the necessary data after creating the ViewModel, but without success.
Model
public class Foo
{
public string Description { get; set; }
}
ViewModel
public class FooViewModel
{
private readonly IUnitOfWork unitOfWork;
private Foo model;
public string Description
{
get => this.model.Description; // <- here occurs the NullRefException after initializing the view
set
{
this.model.Description = value;
this.RaisePropertyChanged();
}
}
public DelegateCommand<Guid> LoadedCommand { get; }
public FooViewModel(IUnitOfWork unitOfWork)
{
// injection of the data access layer
this.unitOfWork = unitOfWork;
// set the loaded command
this.LoadedCommand = new DelegateCommand<Guid>(this.Loaded);
}
public void Loaded(Guid entityId)
{
this.model = this.unitOfWork.FooRepository.GetById(entityId);
}
}
View
<UserControl x:Class="FooView"
prism:ViewModelLocator.AutoWireViewModel="True">
<TextBox Text="{Binding Description}" />
</UserControl>
My problem
The View will be created, but the <TextBox>
already tries to access the Description
. Since model
is null to this time, there will a NullRefException
be thrown. Do you guys have any idea how I can workaround this problem? Thanks in advance!
You have to initialize your model in the FooViewModel constructor: