tags:

views:

51

answers:

1

I have a listbox which has all the names for a list of "Gesture" objects I have.

I want to make it so if I double click on a ListBox item I can then do something with its associated Gesture instance. What is the best way in C# to associate a ListBox item with an instance of a class of mine?

I'm using WPF.

+1  A: 

I am not sure whether I understood your question, but typically, the best way to "associate a ListBox item with an instance of a class" is to simply put the instance itself into the ListBox. You only have to take care of what is displayed for the items. If you have a simple scenario, it might be sufficient to just override the class' ToString() method. If you need a more sophisticated display, you should consider to create DataTemplates for your classes.

If you do not have access to your Gesture classes, you should create a wrapper class for them (something like a ViewModel) and do the proposed adjustments for this wrapper class.

Moreover, you should make all those classes implement a common interface or base class, so that you can safely cast the currently selected item without adding an if-statement for every type that might be in the ListBox.

gehho
How do you feel about the ListBoxItem's "Tag" attribute? Would you suggest against this?
Siracuse
Well, you could also use that property. However, I never use it except for debugging purposes - *very rarely*. I just do not think that this is a good design. And it might/will make problems later on.Why not put the instances itself into the ListBox?
gehho