DataBinding ObservableCollection with WPF

Saturday 24th November, 2007 at 3:51 pm 3 comments

Watch out for the code you place in your sub New() of the ObservableCollection – it can cause the WPF designer problems as the designer will attempt to execute the constructor during design time.  If you’re trying to populate the collection from a file based database then the connection string, in some situations, VS 2008 will look in the wrong place for the database.  It appears that using the |Data Directory| prefix for the database causes VS 2008 (RTM) to look in the working directory of VS – rather than the project directory.

Symptoms of this kind of problem are VS reporting:

“Could not create an instance of type ‘abc’. …Window1.xaml 8 3” and your XAML reference will be squiggily underlined.
A solution to this problem is wraping the constructor of the object implementing the ObservableCollection in a try/catch and swallowing the error (suggested only during the development cycle) or by detecting if you’re in designtime.

A simple way to detect if you’re in designtime with WPF is:

If DesignerProperties.GetIsInDesignMode(Application.Current.MainWindow) Then
  Add(New contact("DesignTime", "Detected"))
Else
  Try
    oContactsTA.Fill(oContacts)
    For Each thisRow In oContacts
      Add(New contact(thisRow))
    Next
  Catch ex As Exception
    Add(New contact("DesignTime", "NotDetected"))
  End Try
End If

Advertisements

Entry filed under: .NET, Visual Studio. Tags: , , .

Surface Computing WPF: Dynamic Filtering Data – the simple approach

3 Comments Add your own

  • 1. Tejas  |  Friday 30th November, 2007 at 3:52 pm

    Sorry! Cant understand.

    Reply
  • 2. Dasher  |  Friday 30th November, 2007 at 5:55 pm

    The code shown is used inside the constructor of the object that inherits from the ObservableCollection.

    The code detects if the collection is being instanced from the designer (ie development) or from the application at runtime.

    Reply
  • 3. Adam  |  Tuesday 1st July, 2008 at 8:24 am

    Awesome!! This was EXACTLY what I needed, thankyou! To get this working in VS2008, i just had to use the System.ComponentModel namespace. Now my User Controls work in design mode. Cheers!

    Reply

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

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts


%d bloggers like this: