TabControl的SelectionChanged事件问题

我正在研究WPF,我正在创建一个userControl,其中包含一个TabControl,它有一些TabItems。

当选定的选项卡发生变化时,我需要执行一些操作,因此,我尝试做的是使用事件myTabControl.SelectionChanged但它被多次引发,即使我只点击一次TabItem。 然后我读了这篇文章is-there-selected-tab-changed-event-in-the-standard-wpf-tab-control并将这段代码放在我的方法中:

 void mainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Source is TabControl) { //do work when tab is changed } } 

在这样做之后,第一个问题已经解决,但是当我运行应用程序并尝试更改选项卡时,出现了错误:

 Dispatcher processing has been suspended, but messages are still being processed 

Visual Studio指向if (e.Source is TabControl) { //here }的第一行代码

但我发现这篇文章选择了change-event-firing-exceptions-for-unknown-cause ,我可以解决这个问题,编写如下代码:

 void mainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Source is TabControl) { if (this.IsLoaded) { //do work when tab is changed } } } 

但是现在我遇到了另一个我无法解决的问题:

事件发射两次! 另一个奇怪的事情是,只有我第一次尝试更改所选标签时,事件才会引发两次,但所选标签仍然是相同的

我希望有人可以帮助我,提前谢谢你。

我想我需要rest一下,因为我的问题真的很傻:

事实certificate,我应该使用TabItem代替TabControl因为它是我感兴趣的控件。

所以,我的代码必须如下:

  void mainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Source is TabItem) { if (this.IsLoaded) { //do work when tab is changed } } }