6

I have a TabControl that has tab bound to a List:

<TabControl ItemsSource="{Binding SomeList}" />

How can find the instances of TabItem? I found other answers that suggest looking at the TabControl.Items list but that is full of Foos. Any idea?

Jake Pearson
  • 27,069
  • 12
  • 75
  • 95

3 Answers3

13

If, for example, you need to get the actual TabItem related to the SelectedItem (which is a bound object) you can use the ItemContainerGenerator as H.B mentioned

var tabItem = this.ItemContainerGenerator.ContainerFromItem(selectedObject);
Oliver
  • 35,233
  • 12
  • 66
  • 78
  • 10
    Thanks for actually ANSWERING the question instead of saying they no one should have to do that. In my case I want to disable the other tabs (without disabling content) when the user makes a change to one of them. – Bill Lefler Nov 05 '15 at 18:56
6

That question gets asked pretty often and the answer always is: Don't do it.

In theory you should not need the TabItem instance because you should bind everything you need to modify. (Also in theory you could get the instance using the ItemContainerGenerator)

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • I have the tabcontrol bound such that some tabitems's visibility may switch to collapsed. If that is the selected tab, I end up with a tab control that looks like no tab is selected. I would like to never end up in that situation. I'll see if I can come up with a more binding oriented solution. – Jake Pearson Mar 08 '12 at 21:08
  • What if it's a control in the tab content that you need? For instance, tab 2 has a listbox control for which I want to grab selected items? I can't necessarily bind selected items to a collection on the view model when the tabs are generated based on another bound collection. Or can I? – Sinaesthetic Sep 15 '15 at 02:43
  • @Sinaesthetic: You commonly bind the selected items by binding the individual items' `IsSelected` property to the item's model/view-model, then you just filter your collection by the bound property. – H.B. Sep 16 '15 at 12:27
  • In theory, end-user should be smart and UI should be intuitive enough. But In real world, It is NOT – deathrace Feb 11 '21 at 12:13
  • @deathrace The point is: A lot of people approach problems the wrong way, because they do not know what the *intended* solution is in WPF. There can be legitimate reasons for getting the UI instance, but in the vast majority of cases you neither need to nor should access the instance. – H.B. Feb 11 '21 at 14:14
1

Long time ago I had a similar problem with the treeview in wpf. I have solved it using ItemContainerGenerator. If you want you can have a look at my solution, maybe it helps you with your problem: How to select a databound TreeViewItem?

But i think H.B. is right with his statement: " [..] you should not need the TabItem instance because you should bind everything you need [..] "

Community
  • 1
  • 1
jwillmer
  • 3,570
  • 5
  • 37
  • 73