Search code examples
c#wpftabitemlostfocus

TabItem LostFocus Event is not firing the first time


I have a TabControl with two TabItems. I have a Thread running in the first tab. When the first tab loses focus, I have to suspend the thread. But I have a small problem with the LostFocus event of the TabItem. The LostFocus event is not triggered the first time the TabItem loses focus, but the second time. Why is this and how do I make it fire the first time?

The following is my xaml code:

<Grid>
    <TabControl Name="tbc">
        <TabItem Name="tabMain" Header="Main" GotFocus="tabMain_GotFocus" LostFocus="tabMain_LostFocus" >
            <uc:ucMain />
        </TabItem>
        <TabItem Name="tabExplorer" Header="Data Explorer">
            <uc:ucExplorer />
        </TabItem>
    </TabControl>
</Grid>

In the above code, uc:ucMain is a UserControl


Solution

  • Seems like this is a weird WPF behavior. You can work around it by force focusing your first TabItem:

    Code:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        tabMain.Focus();
    }