During developing a user control for a WPF UI I encountered a strange null reference exception in the XAML designer.
Strange thing was, that when I started the application and switched to the control which contained the user control, everything worked fine. I could’ve just ignored this problem. However since it is very inconvenient writing XAML code without getting a visual feedback immediately, I needed to find a way to fix this problem.
In the file UserControl.xaml.cs
I had a constructor, which called a method. This method returned data from a database, which I stored in a variable. I had a combobox in the window, in which I inserted the data from the variable mentioned before.
public UserControl() { InitializeComponent(); var dataFromDatabase = GetData(); UserControlCombobox.Itemssource = dataFromDatabase; }
The Editor claimed, that the error occurred on the line where GetData
gets invoked.
The problem was, that the editor already executed the constructor to show and set control properties. Since some objects get instantiated at runtime, a null reference exception was raised from the GetData
method. I needed to implement a switch in the constructor to avoid loading data from database if the constructor got called by the XAML designer.
After a little research, I found the following code snippet:
if (DesignerProperties.GetIsInDesignMode(this)) { return; }
The method DesignerProperties.GetIsInDesignMode
returns true
if the current block is executed by the XAML designer. I added this snippet to the constructor. Since the XAML designer needs to execute the InitializeComponent
method, I inserted the snippet directly after the mentioned method.
public UserControl() { InitializeComponent(); if (DesignerProperties.GetIsInDesignMode(this)) { return; } var dataFromDatabase = GetData(); UserControlCombobox.Itemssource = dataFromDatabase; }
This way the constructor returns without executing GetData
method and the XAML designer worked fine again.