简体   繁体   中英

Better approach for event when tabitem is selected

I have a tabcontrol with 8 tabitems and many many datagrids and listbox inside them. I want to fire up an event only when one specific tabitem is selected.

The first approach is SelectionChanged in tabcontrol with an if statement inside it

If ((thetabiwant!=null)&& (thetabiwant.IsSelected)) 
{
//code here 
}

The second approach is to have a mouseup event in the desired tabitem.

What is the best approach?

(ups and downs is that SelectionChanged fires all the time because of the datagrids while the mouseup event solution doesn't make me happy)

Thanks.

In general, you shouldn't worry too much about fired events that you then skip because they don't match your criteria. The framework itself does that a lot , and you will end up doing a lot of that too (for example when listening to INotifyPropertyChanged events).

In your case, the few additional SelectionChanged events that get fired are really negligible. Each event requires the user to actually change the tab, and that won't happen to often. On the other hand, once you are in the tab you care for, there are actually a lot mouse events happening. Not that you need to care about the number of those either (you really shouldn't unless you get problems) but of course you can avoid it.

So in this case, yes, just skipping the SelectionChanged event is the best approach.

You could also bind the IsSelected Property
In the set do what you need to do when it is changed to true

TabItem.IsSelected

<TabControl Grid.Row="0">
    <TabItem Header="One" IsSelected="{Binding Path=Tab1Selected, Mode=TwoWay}"/>
    <TabItem Header="Two" IsSelected="{Binding Path=Tab2Selected, Mode=TwoWay}"/>
</TabControl>

private bool tab1Selected = true;
private bool tab2Selected = false;
public bool Tab1Selected
{
    get { return tab1Selected; }
    set
    {
        if (tab1Selected == value) return;
        tab1Selected = value;
        NotifyPropertyChanged("Tab1Selected");
    }
}
public bool Tab2Selected
{
    get { return tab2Selected; }
    set
    {
        if (tab2Selected == value) return;
        tab2Selected = value;
        if (tab2Selected)
        {
            MessageBox.Show("Tab2Selected");
            // do your stuff here
        }
        NotifyPropertyChanged("Tab2Selected");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM