我正在研究 WPF,我正在创建一个包含 TabControl 的 userControl,其中包含一些 TabItems。
I need to execute some stuff when the selected tab changes, so, what I tried to do is to use the event myTabControl.SelectionChanged
but it was raised many times, even though I only clicked once a 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
}
}
}
但是现在我遇到了另一个我无法解决的问题:
该事件正在触发两次!另一个奇怪的事情是,只有在我第一次尝试更改所选选项卡时,事件才会引发两次,但所选选项卡仍然相同
我希望有人可以帮助我,提前谢谢你。