【发布时间】:2017-11-18 18:15:33
【问题描述】:
我正在将 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。你们知道我该如何解决这个问题吗?提前致谢!
【问题讨论】:
-
用
string.Empty初始化它,或者只检查Description是否为空,如果是,则返回string.Empty,例如get => this.model.Description ?? string.Empty; -
可能
model?.Description ?? string.Empty更好,否则你仍然得到一个空引用 -
@Haukinger 没错,我错过了。
标签: c# wpf mvvm prism viewmodel