-1

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!

ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
  • Initialize it with `string.Empty` or just check if `Description` is null and if so, return `string.Empty`, e.g. `get => this.model.Description ?? string.Empty;` – FCin Nov 18 '17 at 18:18
  • 3
    probably `model?.Description ?? string.Empty` is better, otherwise you still get a null ref – Haukinger Nov 18 '17 at 18:26
  • @Haukinger True, I missed that. – FCin Nov 18 '17 at 19:16

1 Answers1

0

You have to initialize your model in the FooViewModel constructor:

this.model = new Foo();
TeoVr81
  • 989
  • 15
  • 33