【问题标题】:Load Model after View- and ViewModel-Creation (MVVM)在视图和视图模型创建后加载模型 (MVVM)
【发布时间】: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>

我的问题

将创建视图,但 &lt;TextBox&gt; 已尝试访问 Description。由于此时model 为空,所以会抛出NullRefException。你们知道我该如何解决这个问题吗?提前致谢!

【问题讨论】:

  • string.Empty 初始化它,或者只检查Description 是否为空,如果是,则返回string.Empty,例如get =&gt; this.model.Description ?? string.Empty;
  • 可能model?.Description ?? string.Empty 更好,否则你仍然得到一个空引用
  • @Haukinger 没错,我错过了。

标签: c# wpf mvvm prism viewmodel


【解决方案1】:

你必须在 FooViewModel 构造函数中初始化你的模型:

this.model = new Foo();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多