I made a TabControl and three TabItems inside. My Code looks as follows:
XAML:
<TabControl Name="ConfigTabs" HorizontalAlignment="Left" VerticalAlignment="Top" SelectionChanged="TabControlSelectionChanged">
<TabItem Header="Allgemeines">
...
</TabItem>
<TabItem Header="Monitorbelegung">
...
</TabItem>
<TabItem Header="Produkt-Konfigurationen">
...
</TabItem>
</TabControl>
C# (Code-Behind):
private void TabControlSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.Source is TabControl && this.IsLoaded)
{
TabControl MyTabControl = (TabControl)sender;
if (MyTabControl.SelectedIndex == 0)
{
MessageBox.Show("Allgemeines");
}
else if (MyTabControl.SelectedIndex == 1)
{
MessageBox.Show("Monitor");
}
else if (MyTabControl.SelectedIndex == 2)
{
MessageBox.Show("Configs");
}
}
}
When I change the TabItem, a MessageBox with the Text pops up, as intended. BUT when I now click another Item I get the MessageBox of the next Item AND afterwards a MessageBox of the past one. Where I am not completly sure of the logic behind that. When I delete the MessageBoxes everything works fine, but I need them, because of some logic I want to implement at a later time.
The Question would be now "How can I prevend the event from firing twice?";
Ok, I found it. The MessageBox interrupts the change-event, so we have to use some other way. When you use a style, you can catch the change-event of the TabItems:
XAML:
<TabControl Name="ConfigTabs" HorizontalAlignment="Left" VerticalAlignment="Top">
<TabControl.Resources>
<Style TargetType="TabItem">
<EventSetter Event="Selector.Selected" Handler="OnNewTabSelected"/>
</Style>
</TabControl.Resources>
<TabItem Header="Allgemeines">
...
</TabItem>
<TabItem Header="Monitorbelegung">
...
</TabItem>
<TabItem Header="Produkt-Konfigurationen">
...
</TabItem>
</TabControl>
C# (Code-Behind):
private void OnNewTabSelected(object sender, RoutedEventArgs e)
{
if (e.Source is TabItem && this.IsLoaded)
{
TabItem MyTab = (TabItem)sender;
TabControl MyControl = (TabControl)MyTab.Parent;
if (MyControl.SelectedIndex == 0)
{
MessageBox.Show("Beep" + MyControl.SelectedIndex);
}
else if (MyControl.SelectedIndex == 1)
{
MessageBox.Show("Beep" + MyControl.SelectedIndex);
}
else if (MyControl.SelectedIndex == 2)
{
MessageBox.Show("Beep" + MyControl.SelectedIndex);
}
}
}