Here is what i have:
- a SQL CE database, that holds this
Categorytable, 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> 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.
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