Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically select a TabItem in WPF TabControl

I would like to know how to select a specific TabItem in a WPF TabControl.

I tried these bellow but nothing work!

MyTabControl.SelectedIndex = x

MyTabControl.SelectedItem = MyTabItem

MyTabControl.SelectedValue = MyTabItem

MyTabItem.IsSelected = True
like image 938
Pierre Toutant Avatar asked Oct 28 '11 13:10

Pierre Toutant


3 Answers

As @Chris says, any of the first three things should work and as @Phyxx says, it doesn't always really work. The problem is some subtle thing about the order of property changes. To work around it you need to let the WPF invoke your tab-selection code in its own time:

Dispatcher.BeginInvoke((Action)(() => MyTabControl.SelectedIndex = x));

This does just what Phyxx' timer does, but in a slightly less extreme way.

like image 63
Adrian Ratnapala Avatar answered Nov 18 '22 01:11

Adrian Ratnapala


All your examples except the third one are correct and will work. The problem must be at another location. Maybe you reset the item after setting or your code never is called?

Valid

MyTabControl.SelectedIndex = x   
MyTabControl.SelectedItem = MyTabItem    
MyTabItem.IsSelected = True 

Invalid

MyTabControl.SelectedValue = MyTabItem 
like image 31
HCL Avatar answered Nov 17 '22 23:11

HCL


Loop through the TabItems and for the tab to be selected, set

tabItem.IsSelected = true

If there are any other place due to binding changing you will see problem. Otherwise, the above code should work.

like image 17
kishhr Avatar answered Nov 18 '22 01:11

kishhr