I have a TabControl in WPF. I want to find an event that occurs when changing tabs. What is the name of this event?
Asked
Active
Viewed 3.2k times
14
-
5At least show some research effort. should be downvoted for sheer laziness. – Nasreddine Nov 17 '11 at 18:18
3 Answers
28
The TabControl
inherits from a Selector
which contains the SelectionChanged
event.
<TabControl SelectionChanged="OnSelectionChanged" ... />
private void OnSelectionChanged(Object sender, SelectionChangedEventArgs args)
{
var tc = sender as TabControl; //The sender is a type of TabControl...
if (tc != null)
{
var item = tc.SelectedItem;
//Do Stuff ...
}
}

myermian
- 31,823
- 24
- 123
- 215
-
6You cannot can get an TabItem as a sender from a TabControl, the sender will be a TabControl – Butzke Jul 02 '15 at 16:45
-
1I think for this to work you would need to cast the sender to a TabControl `var tabControl = (TabControl) sender;` then cast the selected item to a TabItem `var tab = (TabItem) tabControl.SelectedItem;` – ChrisProsser Mar 31 '16 at 17:08
4
I just want to add my point here. And I will use cool answer of @pratap k to do it.
<TabControl x:Name="MyTab" SelectionChanged="TabControl_SelectionChanged">
<TabItem x:Name="MyTabItem1" Header="One"/>
<TabItem x:Name="MyTabItem2" Header="2"/>
<TabItem x:Name="MyTabItem3" Header="Three"/>
</TabControl>
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (MyTabItem1 !=null && MyTabItem1.IsSelected)
// do your staff
if (MyTabItem2 !=null && MyTabItem2.IsSelected)
// do your staff
if (MyTabItem3 !=null && MyTabItem3.IsSelected)
// do your staff
}
As you see the difference is to add checking for NULL
.
That is it!

NoWar
- 36,338
- 80
- 323
- 498
4
I didn't get the selected answer to work, maybe something has changed, maybe my setup is different.
My solutions is straightforward, you cast the sender to become the tabControle. Then you pull out the selected TabItem (selectedValue) and cast this to an TabItem.
In my situation, I need to know "who" changed, so I look for the name of the TabItem, to better react to a specific event.
XAML
<TabControl SelectionChanged="OnTabItemChanged">
<TabItem Name="MainTap" Header="Dashboard"></TabItem
</TabControl>
C#
private async void OnTabItemChanged(object sender, SelectionChangedEventArgs e)
{
TabControl tabControl = sender as TabControl; // e.Source could have been used instead of sender as well
TabItem item = tabControl.SelectedValue as TabItem;
if (item.Name == "MainTap")
{
Debug.WriteLine(item.Name);
}
}

Christopher Bonitz
- 828
- 1
- 10
- 22