1

I'd like to set focus to TabControl's current selected TabItem's content.

I'm binding items via ItemsSource, so I don't have simple access to TabItems themselves;

I also cannot call Focus() on TabControl, because it focuses the TabControl itself instead of its content (for this one I did a crude, but effective check - made a DispatcherTimer, which emitted current focused item once a second).

Effectively I want to achieve the same effect as clicking on currently selected tab's header. How can I do that (not doing that quick&dirty by simulating the click, of course)?

Spook
  • 25,318
  • 18
  • 90
  • 167
  • Does this answer your question? [How can I make a specific TabItem gain focus on a TabControl without click event?](https://stackoverflow.com/questions/1227132/how-can-i-make-a-specific-tabitem-gain-focus-on-a-tabcontrol-without-click-event) – Pavel Anikhouski Mar 05 '20 at 13:12
  • @PavelAnikhouski Doesn't seem so. That question asks about selecting tab. I'm asking about focusing content of already selected tab. – Spook Mar 05 '20 at 13:24
  • Do you want to always set focus on the `TabItem` content on selection or just when you need to? – Nicke Manarin Mar 05 '20 at 14:10
  • @Spook could you please provide your xaml of tab items ? – Sats Mar 05 '20 at 14:10
  • @Spook, isn't `((this.yourTabControl.SelectedItem as TabItem).Content as UIElement).Focus();` working for you? – Mike Mar 05 '20 at 14:18

1 Answers1

0

You could extend your TabControl and override the OnSelectionChanged method.

protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
    //TODO: Ignore this event on load.

    if (e.AddedItems.Count > 0)
        ((e.AddedItems[0] as TabItem)?.Content as UIElement)?.Focus();

    base.OnSelectionChanged(e);
}
Nicke Manarin
  • 3,026
  • 4
  • 37
  • 79