views:

215

answers:

2

Here is what i have:

  • a SQL CE database, that holds this Category table, with id and name columns only.
  • dbml generated with sqlmetal
  • singleton (static class) that exposes the linq DataContext.
  • in the code-behind file, i have a property like follows:

    private System.Data.Linq.Table Categories { get { return LibraryDataStore.Instance.Categories; } }

I want to simply bind the categories to a combobox. Can't believe i've been at it for hours now, with no result :( I don't want to set ItemsSource in the code behind, I want to do this XAML-only, but how? Most examples i found were defining the data right there in XAML, or setting ItemsSource programatically, but that is not what i want.

Why isn't this, for example, working?

            <ComboBox Name="cmbCategory" 
                      Margin="3" 
                      MinWidth="200" 
                      ItemsSource="{Binding Path=Categories}" 
                      DisplayMemberPath="Name"/>

As a side note, i want to say that I find the databinding model of wpf extremely difficult to learn, as it is so thick and there are just SO MANY WAYS to do things.

Later edit: I found that it works if i set the ItemsSource like this:

        var cats = from c in LibraryDataStore.Instance.Categories
                   select c;

        cmbCategory.ItemsSource = cats;

Still, I can't figure it out why it doesn't work in XAML.

A: 

you need to set the DataContext of your UserControl (or Page) to the current instance :

this.DataContext = this;
Thomas Levesque
Teodor
+2  A: 

You must set the datacontext of the UserControl to LibraryDataStore.Instance. This datacontext will then filter down the visual tree to your combobox (so there is no need to set the datacontext of the combobox itself). Your xaml will then be able to bind to the public property of this object "Categories".

Bea Stollnitz gives a good overview of how to detect problems with databinding (i.e. it failing silently) on her blog -> http://bea.stollnitz.com/blog/?p=52

mattythomas2000
it works :) thanksStill i don't understand why is it different when i set the DataContext to "this", and also expose a property that is wrapped over LIbraryDataStore.Instance.Categories. But it doesn't matter now, since that approach was kind of silly anyway.
Teodor
By the way, that's a great blog post by Bea Stollnitz.
Teodor