1

So it seems like what I want to do should be straightforward, but I haven't been able to find a way to do it...

I need to display a list of objects that represent custom elements for entering data. Exactly how each object is displayed depends on the parameters of the object - so it could be a grid containing a name, description, and text box. It could be a grid with a couple labels and a dropdown. It could be an expander that contains multiple sub-objects. It could be something new that hasn't been built yet (so it needs to be extensible). Right now, I am populating this list by creating the FrameworkElement for each object and then adding it to a Grid by hand.

I would like to switch to keeping my objects in an ObservableCollection, and then binding that collection to a ListBox (or similar). That way, when new objects are added or removed from the list, the UI would automatically update itself accordingly. What I can't figure out is, is there a way to point it to my C# method for creating the custom-configured FrameworkElement for each object, so that when new objects are added the appropriate elements will be added to the UI?

Kevin Dill
  • 186
  • 1
  • 10

2 Answers2

3

Well, you're on the right track as far as wanting to use an ObservableCollection<T> and a ListBox control. Though, I'd venture to say you might want to simply use an ItemsControl since you probably don't care about selecting a particular item, but merely displaying an enumeration of items, and the ListBox would allow you to actually select one of those items.

Your problem is that you want each item in the list to display differently depending on certain criteria. For this you'll want to look at the DataTemplate and DataTemplateSelector classes.

Basically, a DataTemplate is a way of saying "I want my item to look like this.", and a DataTemplateSelector is a way of saying "I want to select this specific DataTemplate based on this criteria."


Here are a few examples on how to use the DataTemplate/DataTemplateSelector classes:

myermian
  • 31,823
  • 24
  • 123
  • 215
1

Seperating the presentation from the model is always a good idea. It seems like you are on the right track.

Foreach object type, you should create a DataTemplate and then use ItemTemplateSelector to select the correct template for each object type.

Good luck

Esti
  • 3,677
  • 8
  • 35
  • 57
Moran Moshe
  • 114
  • 1