XAML

Prevent XAML designer and editor error caused by viewmodel initialization

The viewmodel’s constructor are being used by the designer to show some design time data. If the constructor has some dependencies that cannot be resolved, we can get an error in the xaml editor or designer. This is the reason why sometimes we can see the error in the designer or editor but when we run the app, there’s actually no error.

First thing to do is to identify all the dependencies within the cosntructor that needs to be resolved. If those dependencies cannot be resolved at design time, we have to put it inside the IsInDesignMode block or any other condition that checks if it’s currently in design mode.

example:

public MainPageViewModel()
{
	this.Items = dataService.GetItems();
}

In the code above, we have a dependency in dataService. When the designer called the constructor, It will not have any idea about the dataService, therefore it will give us an error in the xaml.

We can use IsInDesignMode (MvvmLight) to prevent those errors. IsInDesignMode is a property within the ViewModelBase class of MVVM Light. But we can also implement it on our own.

public MainPageViewModel()
{
	if(!IsInDesignMode)
		this.Items = dataService.GetItems();
}

But what if we want to put something in the Items to show in the designer? Just put it in the else block, those those will be your design time data and it will not show up on runtime.

public MainPageViewModel()
{
	if(!IsInDesignMode)
	{
		this.Items = dataService.GetItems();
	}
	else
	{
		this.Items = new List<ItemModel>();
		this.Items.Add(/* Add something */);
		this.Items.Add(/* Add something */);
		//...
	}
}

 

Aside from preventing error, it will also improve the xaml editor’s intellisense.

Advertisements

One thought on “Prevent XAML designer and editor error caused by viewmodel initialization

  1. I ran into a similar problem with Prism 6, when added a project called Styles to the solution, in which I had a folder named themes that held all my ResourceDictionaries. After reading this post, I just added an empty constructor to the Styles project, and the XAML editor was happy. Thanks for this post!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s