Siracuse
Siracuse

Reputation: 551

How should I associate a ListBox item with an item in a list of mine?

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.

Upvotes: 0

Views: 520

Answers (1)

gehho
gehho

Reputation: 9238

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.

Upvotes: 1

Related Questions