Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Loading data in the constructor of a UserControl breaks the Designer

I have a main window with a usercontrol. When adding code in the default constructor of the usercontrol, the designer stops showing the main window. It gives a message:

Problem loading

The document contains errors that must be fixed before the designer can be loaded.
Reload the designer after you have fixed the errors.

Reload the designer

Why is this?

This is the code that I have in the constructor:

using (var context = new Data.TVShowDataContext())
{
    var list = from show in context.Shows
               select show;

    listShow.ItemsSource = list;
}

If I can't use the constructor to fill gui with data, when should I else do it? Would it be better to do this with binding? Any sugestions how?

like image 662
Vegar Avatar asked Feb 20 '09 19:02

Vegar


1 Answers

The WPF designer will execute the constructor on child elements when displaying them. My guess is that you've got code in the constructor that throws an exception at design-time, probably because it's using an object that's only available at run-time. A solution would be to surround your constructor logic with a check to prevent it from executing while it's being displayed in the designer.

if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
  using (var context = new Data.TVShowDataContext())
  {
    var list = from show in context.Shows
               select show;

    listShow.ItemsSource = list;
  }    
}
like image 166
BadCanyon Avatar answered Sep 22 '22 00:09

BadCanyon