Jarred Sumner
Jarred Sumner

Reputation: 1853

Storing object within TreeViewItem?

I want to store an instance of a class within a TreeViewItem so that way I don't have to make the program sort through the list of possibly selected items for it.

I.e something that might look like

Bagel Poppyseed = new Bagel();    
TreeViewItem TreeViewPoppyseed = new TreeViewItem();
TreeViewPoppyseed.Bagel = Poppyseed;

So that way whenever TreeViewPoppyseed is selected, there would be no need to run a different method to get the instance of Bagel it has. It can just be like TreeView.SelectedItem.Bagel;

Does something like this already exist?

Upvotes: 1

Views: 577

Answers (2)

wangburger
wangburger

Reputation: 1083

You can make a data template for the tree view item and then you can access the DataContext property to get the bound object.

in an event handler:

TreeViewItem tvi = (TreeViewItem)sender;
Bagel bagel = (Bagel)tvi.DataContext;
//do whatever you want with bagel and tree view item

Upvotes: 1

Josh M.
Josh M.

Reputation: 27783

This is what the Tag property is for, you can throw your object in there and retrieve it later.

See here: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.tag.aspx

Also, if your data-binding to that object, then it would be in the DataContext property.

Upvotes: 4

Related Questions