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 TreeVi开发者_如何学JAVAewPoppyseed 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?
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.
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
精彩评论