syncis
syncis

Reputation: 1433

How do I display a property from a child element in a ListBox bound with ItemsSource?

I can't figure this out, consider the following code:

 <ListBox Width="200" 
          ItemsSource="{Binding CurrentArticle.ArticleCategories}" 
          DisplayMemberPath="{Binding Category.Name}">
  </ListBox>

ArticleCategories is a table in my database that contains 2 foreign keys, 1 to Article and 1 to Categories, so ArticleCategories is a list that contains Articles and Categories.

I want to show which categories the current article(CurrentArticle) have in this listbox and I can't figure out how to do so. I want to show Category.Name for each Category in the ListBox.

Right now, the listbox is showing "Data.ArticleCategory" because it dont know how to display it.

I have tried DisplayMemberPath="Category.Name" without success.

Do I need to use some sort of Data Template, if so, how?

Thank you.

Upvotes: 3

Views: 339

Answers (3)

Josh C.
Josh C.

Reputation: 4363

You can set the ListBox.ItemTemplate with a datatemplate that looks the way you like: http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplate.aspx

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292465

You don't need a binding:

DisplayMemberPath="Category.Name"

EDIT: since you're binding ItemsSource to CurrentArticle.ArticleCategories, I assume that the items of your ListBox are objects of type Category? in that case the path should be just "Name", not "Category.Name".

Upvotes: 3

dowhilefor
dowhilefor

Reputation: 11051

DisplayMemberPath is not a field where you add a binding, its just the name of your Property on the given Item. DisplayMemberPath="Name" should be enough.

Upvotes: 4

Related Questions