Search code examples
c#wpfmessagebox

Tab does not navigate after adding MessageBox on the tab's PreviewMouseDown Event


i have a WPF tab control with two tabs(A, B). Since there is no Clicked Event on the TabItem,therefore i add an previewMouseDown event on the Tab B and a messageBox will show up. However, after i close the messageBox, my application will not navigate to the Tab B. Anyone can help me?

C# code snippet :

  private void MyTabB_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        MessageBox.Show("Please login");
    }

Solution

  • You can use the TabControlSelectionChanged event.

    Since you know the selected tab for login say index 0, change selected tab after the MessageBox ie something like this

    MyTabB_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
         TabControl tc= ((TabControl)sender;
         if(tc.SelectedIndex == tc.Items.IndexOf(A/*Login tab*/))
          {
             MessageBox.Show("Login")
             tc.SelectedIndex = tc.Items.IndexOf(B);
          }
    }
    

    This means whenever you select A you will MessageBox will pop up then you login.

    Alternatively why not put a button or any control with ClickedEvent in A then when clicked tc.SelectedIndex is changed.