开发者

How do I bind a lookup combobox?

My WPF4 combobox dropdown list is incorrectly displaying the class name of my EF4 entity. Here is the relevant XAML:

<Window.Resources>
    <CollectionViewSource x:Key="myEntitiesViewSource"/>
</Window.Resources>

<ComboBox ItemsSource="{Binding Source={StaticResource myEntitiesViewSource}}" DisplayMemberPath="CategoryDescription" SelectedValuePath="CategoryID" />

Here is the code in my Window_Loaded event:

var categoryList = from p in _context.Categories
           开发者_StackOverflow社区       orderby p.CategoryNumber
                  select p;

System.Windows.Data.CollectionViewSource myEntitiesViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("myEntitiesViewSource")));
// Load data by setting the CollectionViewSource.Source property:
myEntitiesViewSource.Source = categoryList;

My database has a many to many relationship between Projects and Categories with a join table called ProjectCategories. The Categories entity was automagically created as a single entity to represent two database tables:

1) the lookup table of Categories containing an ID, CategoryDescription and CategoryNumber and

2) the join table ProjectCategories containing only two fields - the IDs from the tables Projects and Categories. The entity model lives in a separate project from my WPF window.

My goal is to allow the user to select a CategoryDescription from the dropdown list, then click an Add Category button to add the selected Category to a separate list of ProjectCategories. With the current code I see the correct CategoryDescription in the combobox text area but the dropdown list displays only the entity class name Categories (preceded by it's namespace) multiple times!

How do I make this simple lookup combobox bind correctly and display a list of CategoryDescriptions and a SelectedValue of CategoryID? Note: I'd accept a code only approach leaving out the CollectionViewSource in XAML if it's possible.

Thanks!


Nevermind. I asked this question and have answered it myself. There was nothing wrong with my code or XAML. The problem was caused by the use of a third party theme to style my controls. Once I removed the theme the combobox binding problem went away. For more details see this post.


What about something like this?

<ComboBox  ItemsSource="{Binding Categories}" 
           SelectedItem="{Binding Category}" DisplayMemberPath="Description" />

Instead of using a Selected Value, I would store the whole object. The selected value approach is old ASP style for my taste.

SelectedItem="{Binding Category}" is your Category object. Basically it has stored the selected item of the ComboBox.

When the user clicks a button for example, you can fire a Command from the ViewModel and you will have the corresponding selected Category object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜