【问题标题】:How to add tab items to existing tab control from user Control in wpf如何从 wpf 中的用户控件将选项卡项添加到现有选项卡控件
【发布时间】:2012-01-25 08:34:46
【问题描述】:

我有 MainWindow 和 2 个用户控件。如果您单击 MainWindow 中的按钮搜索,则在主窗口中有一个选项卡控件,它会加载用户控件。我可以通过这段代码在主窗口中添加标签项。

 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);
         }

当用户控件 1 在选项卡项中加载时。用户控件 1 中有 Tetxbox 和按钮。我想在单击按钮时加载用户控件 2。但是我无法从用户控件 1 访问主窗口中的选项卡控件。请给我指导。在哪里挖?

【问题讨论】:

    标签: wpf


    【解决方案1】:

    您可以使用扩展方法在 VisualTree 中搜索类型为 TabControl 的父级。

    例如

    扩展方法:

      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);
          }
        }
    

    在您的按钮处理程序中:

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

    更好、更灵活(但也更复杂)的解决方案是通知参与者(这里:您的 Button 会触发某种消息,表明它已被点击,其他人(您的 TabControl)会监听并对其做出反应(创建一个新的标签)。 例如,这可以通过 Mediator 模式或 EventAggregator 来完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2011-10-24
      • 1970-01-01
      相关资源
      最近更新 更多