Firdavs Kurbonov
Firdavs Kurbonov

Reputation: 1252

How to add tab items to existing tab control from user Control in wpf

I have MainWindow and 2 user controls. In Main Window there is Tab Control which loads User Control if you click on button search in MainWindow. I could add tab items in main Window by this code.

 private void search(object sender, RoutedEventArgs e)
        {

            tc.Visibility = Visibility.Visible; // It is hidden by default
            TabItem tab = new TabItem();
            tab.Header = "Поиск";
            UCSearch c = new UCSearch(); // User Control 1
            tab.Content = c;
            tc.Items.Add(tab);
         }

When User Control 1 is loaded in Tab item. There is Tetxbox and Button in User Control 1.I want to load User Control 2 when is clicking to Button. But I can not get access to Tab Control which is in Main Window from User Control 1. Please Give me direction. Where to dig?

Upvotes: 0

Views: 1333

Answers (1)

SvenG
SvenG

Reputation: 5195

You could use an Extension method to search the VisualTree for a Parent of type TabControl.

e.g.

Extension method:

  public static class VisualTreeExtensions
  {

    public static T FindParent<T>(this DependencyObject child)
  where T : DependencyObject
    {
      //get parent item
      DependencyObject parentObject = VisualTreeHelper.GetParent(child);

      //we've reached the end of the tree
      if (parentObject == null) return null;

      //check if the parent matches the type we're looking for
      var parent = parentObject as T;
      if (parent != null)
      {
        return parent;
      }
      else
      {
        return FindParent<T>(parentObject);
      }
    }

In your Button Handler:

private void Button_Click(object sender, RoutedEventArgs e)
{
  var tabControl = (sender as Button).FindParent<TabControl>();
  tabControl.Items.Add(new TabItem() { Header = "New"});
}

The better and more flexible (but also more complicated) solution would be to notify the participants (here: your Button fires some kind of message that it was clicked, others (your TabControl) listen and react on it (create a new Tab). This can for example be done with a Mediator pattern or an EventAggregator.

Upvotes: 1

Related Questions