我在里面制作了一个TabControl和三个TabItems。我的代码如下:
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");
}
}
}
当我更改TabItem时,会弹出一个带有文本的MessageBox,如预期的那样。但是,当我现在单击另一个项目时,我得到下一个项目的MessageBox,然后是过去的一个MessageBox。我完全不确定其背后的逻辑。 当我删除MessageBoxes时,一切正常,但我需要它们,因为我想在以后实现一些逻辑。
问题现在是“如何通过两次射击来预防事件?”;
答案 0 :(得分:0)
好的,我找到了。 MessageBox中断了change-event,所以我们必须使用其他方法。使用样式时,可以捕获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);
}
}
}