0
ObservableCollection<Cat> cats = new ObervableCollection<Cat>
{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 },
new Cat{ Name = "Sasha", Age=14 }
};    

How can I access these instances?

Consider these instances are created to add treeViewItems (by assigning the above collection as ItemSource). I want to create one tabItem for one treeViewItem while Double Clicked on TreeViewItem, and I want to assign/use the above instance for storing the data from TabItems.

Consider a WPF window, which has TreeView on the left side and TabControl (in which I am creating TabItems) on the right side. When I populate the TreeView, I do above operation of adding instances to ObservableCollection. Then I want the TabItems (In TabControl) to have the same instances which are used to populate the TreeView.

Edit: * Creating Tabitems is not a problem here. But assigning/using the same instance that I used for populating TreeView is the problem. I am not able to get the same instance.

Anroop
  • 41
  • 4
  • what about `cats[index].Name` ? – michasaucer Jan 24 '19 at 11:06
  • 1
    Could you elaborate how it should look like? I'm confused by your `TabItem`/`TreeViewItem` description. – LittleBit Jan 24 '19 at 11:11
  • To access instance you have to find it (enumerate the list) by knowing something, e.g. index or maybe unique value (is `Name` unique?). If collection is big and you search often - consider to use specialized collections (dictionaries). But since your question is tagged [tag:mvvm] you could simply pass double-clicked item as command parameter, then [find its index](https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.indexof?view=netframework-4.7.2) - previous item would be `index - 1`. – Sinatr Jan 24 '19 at 11:11
  • https://stackoverflow.com/questions/1000040/data-binding-to-selecteditem-in-a-wpf-treeview check this to see how to handle the selection of the treeview. In your handler you just need to send to your viewmodel the Cat object, and then open a new tab with the info you gathered – Daniele Sartori Jan 24 '19 at 11:14
  • It sounds like you should just enumerate the `cats`, by using `foreach(var cat in cats){ CreateCatTab() }` – Robin Bennett Jan 24 '19 at 11:36
  • Similar to TreeView, TabControl is an ItemsControl. If you assign the same collection of items to the ItemsSource property of both a TreeView and a TabControl, the TabControl automatically creates a TabItem for each top-level TreeViewItem. – Clemens Jan 24 '19 at 12:01
  • If you want to access only the selected item in the TreeView, use its SelectedItem property. It return a Cat instance or null when none is selected. Besides that, why are you using a TreeView for data that is apparently not hierarchical? Better use a ListBox or ListView. – Clemens Jan 24 '19 at 12:02

0 Answers0