我正在使用WPF和Prism框架。我试图实现加载必要的数据after creating the ViewModel,但没有成功。
模型
public class Foo
{
public string Description { get; set; }
}
视图模型
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);
}
}
查看
<UserControl x:Class="FooView"
prism:ViewModelLocator.AutoWireViewModel="True">
<TextBox Text="{Binding Description}" />
</UserControl>
将创建视图,但<TextBox>
已尝试访问Description
。由于此时model
为空,因此会抛出NullRefException
。你们有什么想法我可以解决这个问题吗?提前谢谢!
答案 0 :(得分:0)
您必须在FooViewModel构造函数中初始化模型:
this.model = new Foo();