How to make WPF ViewModel that will not crash during design time

Hello everybody,

today I want to describe following WPF use case: you make your View in xaml, then add some ViewModel in which instantiate reading from repository, and then try to open some that ViewModel in designer and see error message. Pretty disappointing situation, isn't it?

In order to avoid such a situation, inside of your constructor of your ViewModle use DesignerProperties class, and it's method GetIsInDesignMode. If it returns true, it means that you try to see control in design mode, and then instead of executing some produciton code you can either return some hardcoded values for design time, or at least return from the construction. 

For example like this:

public class StudentsListViewModel
{
    private IStudentsRepository _repository = new StudentsRepository();
    
    public StudentsListViewModel()
    {
        if (DesignerProperties.GetIsInDesignMode(
            new System.Windows.DependencyObject())) return;
 
        Students = new ObservableCollection<Student>( _repository.GetStudentAsync().Result);
    }

with such approach your controls will stop crashing during design, and give you some ideas on how they will look like. 

No Comments

Add a Comment