TabControl 的 SelectionChanged 事件问题 [英] TabControl's SelectionChanged event issue

查看:33
本文介绍了TabControl 的 SelectionChanged 事件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on WPF and I am creating a userControl which contains a TabControl which has some TabItems.

我需要在选定的选项卡更改时执行一些东西,所以,我尝试做的是使用事件 mytabcontrol.selectionChanged ,但它是多次提出的,即使我只点击一次一个选项卡.然后我读了这篇文章 is-there-selected-tab-changed-event-in-the-standard-wpf-tab-control 并将此代码放入我的方法中:

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. Then I read this post is-there-selected-tab-changed-event-in-the-standard-wpf-tab-control and put this code inside my method:

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

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

After doing that the first problem had been solved, but then when I ran the application and tried to change of tab, an error was raised:

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

Visual Studio 指向 if (e.Source is TabControl) {//here }

Visual Studio points to the first line of code inside of if (e.Source is TabControl) { //here }

但我发现这篇文章selectionchanged-event-firing-exceptions-for-未知原因,我可以写一些代码来解决这个问题,如下所示:

But I found this article selectionchanged-event-firing-exceptions-for-unknown-reasons and I could solve that problem writing some code as below:

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

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

But right now I am having another problem which I havent been able to solve:

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

希望有人能帮助我,在此先感谢您.

I hope someone can help me, thank you in advance.

推荐答案

我觉得我需要休息一下,因为我的问题真的很傻:

I think I need to take a rest, since my problem is really silly:

事实证明,我应该使用 TabItem 而不是 TabControl,因为它是我感兴趣的控件.

Turns out that instead of TabControl I should have used TabItem since it is the control I am interesting in.

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

So, my code has to be as below:

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

这篇关于TabControl 的 SelectionChanged 事件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆