views:

19

answers:

2

Hey all,

I have a ListBox which I am using to display the results of various searches. Those searches can occur on many different types of objects and I'm having a bit of trouble getting it to work in all circumstances.

Most of the time I can just set ListBox.ItemSource = List and it's works fine if I also set the DisplayMemberPath and the SelectedValuePath. I run into trouble when the string I'd like to display for a given object is actually a method or a combination of properties.

Can someone please point me in the correct direction for solving this problem?

Thanks,
Sonny

A: 

Funny, I just asked a very similar question about the DataGrid.

What you could do is create a custom collection of ListBoxItem objects for every type of search object and add those items to the ListBox at runtime.

List<ListBoxItem> lbiTest = GetListBoxItems();
foreach (ListBoxItem lbi in lbiTest)
{  
  lbMyListBox.Items.Add(lbi);
}
kzen
Doesn't adding the items into my ListBox manually defeat the purpose of DataBinding?
Sonny Boy
That was my question exactly... it is also going against the MVVM guidelines by making your ViewModel aware of specific UI controls... hopefully someone could share some good insight...
kzen
+1  A: 

There a couple of options I can think of.

  1. Create a datatemplate for each object in the listbox
  2. Create a wrapper class and bind your listbox to a list of those wrapper classes. It would take a little work to create a constructor (or other method) for every possible search result class.
mdm20
#1 did the trick. I set the different templates in the code behind with something like this: `this.lstSearchResults.ItemTemplate = (DataTemplate)this.FindResource("clientListing");` where "clientListing" is the name of the template I wanted to use. :)
Sonny Boy
If you set the TargetType in your datatemplate and get rid of the key, I don't think you even have to set the itemtemplate.. it will find it automatically.
mdm20