0

I am new to WPF, and I want to do something when a user switches between my tabcontrol items. As expected, I had the issue of firing the selectionchanged event multiple times, then I read this post:

In C# WPF, why is my TabControl's SelectionChanged event firing too often?,

and I don't like the first solution which requires too many extra code for handling event for each selectors in the application. Hence, I tried the solution in this post:

TabControl's SelectionChanged event issue,

but I got a new issue that I couldn't find any related post in stackoverflow.

The problem I have is that the following code doesn't return true:

if (e.Source is TabControl){ // do something }

neither this one:

if (e.Source is TabItem) {// do something}

When I hover on the e.Source in debug mode, it shows as

{System.Windows.Controls.TabControl Items.Count:5}

and if I tried to view it in WPF Tree Visualizer, it tells me that it is the TabControl that I expected for.

So my question is, why it doesn't return true since it is a TabControl?

Here is my code for SelectionChanged:

    void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.Source is TabControl)
        {
            if (item1.IsSelected)
            {
                myllist1.DataContext = getList1();
            }
            else if (item2.IsSelected)
            {
                mylist2.DataContext = getlist2();
            }
            else if (item3.IsSelected)
            {
                mylist3.DataContext = getlist3();
            }
            else if (item4.IsSelected)
            {
                mylist4.DataContext = getlist4();
            }
        }
    }
Community
  • 1
  • 1
yan
  • 55
  • 1
  • 1
  • 6

1 Answers1

1

You have to convert e.source from an Object to a FrameworkElement, and then compare the types.

if (((FrameworkElement)e.Source).GetType()== typeof(System.Windows.Controls.TabControl))
  {
   if (item1.IsSelected)
        {
            myllist1.DataContext = getList1();
        }
        else if (item2.IsSelected)
        {
            mylist2.DataContext = getlist2();
        }
        else if (item3.IsSelected)
        {
            mylist3.DataContext = getlist3();
        }
        else if (item4.IsSelected)
        {
            mylist4.DataContext = getlist4();
        }
  }
deskplace
  • 36
  • 3
  • BTW, I am just curious that in all those posts I have read, nobody raised this question, so I guess they all run good without converting? – yan Aug 13 '14 at 15:42
  • They may not have other controls on tabitems that bubble up the selectionchanged event (which is the problem), or they may have set e.handled=true on every control that bubbles up to that event so that it never reaches the container event. I'm glad I helped, though! – deskplace Aug 13 '14 at 15:59