我正在从事WPF开发并创建了一个用户控件,其中包含一个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 }
代码块的第一行。
但我在这篇文章selectionchanged-event-firing-exceptions-for-unknown-reasons中发现了一些有用的信息,通过编写以下代码,我成功解决了这个问题:
void mainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.Source is TabControl)
{
if (this.IsLoaded)
{
//do work when tab is changed
}
}
}
但是现在我遇到了另一个问题,我还没有解决:
事件会触发两次!还有一件奇怪的事情是,只有第一次尝试更改选定选项卡时,事件会触发两次,但选定的选项卡仍然是相同的
希望有人能帮助我,提前致谢。