如何动态创建tabControl的Item

2024-12-14 19:03:19
推荐回答(1个)
回答1:

1.TabControlDemo.xaml是主界面

   
       
           
           
       

       
           
           
       

       

           
           
           

       
       

       

   

 

2.TabControlDemo .cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Silverlight.Common.View
{
    public partial class TabControlDemo : UserControl
    {
        public TabControlDemo()
        {
            InitializeComponent();
        }

 

  //header是tabItem的标题,typeName是所显示界面的全名(命名空间+类名)

        private void AddTabItem(string header, string typeName)
        {
            if (string.IsNullOrEmpty(header) || string.IsNullOrEmpty(typeName))
            {
                return;
            }

    //获取已经显示的TabItem,将TabItem的header作为检索条件

        var list = this.tabControl.Items.Where(w => ((TabItem)w).Header.ToString() == header);

    //如果所点击的窗体已打开,那么显示该窗体,这样避免打开多个同一窗体           

    if (list.Count() > 0)
            {
                ((TabItem)list.First()).Visibility = Visibility.Visible;

                this.tabControl.SelectedItem = list.First();
            }
            else
            {
                TabItem tabItem = new TabItem();

                tabItem.Header = header;

      //用发射实例化窗体类
                var tabContent = Activator.CreateInstance(Type.GetType(typeName)) as UserControl;

                tabItem.Content = tabContent;

        //将实例化的tabItem添加到TabControl
                this.tabControl.Items.Add(tabItem);
                this.tabControl.SelectedItem = tabItem;
            }
        }

        private void DataGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

    //Silverlight.Common.View.DataGridDemo是SilverLight学习笔记七DataGrid控件节中的DataGridDemo(DataGrid控件)
            this.AddTabItem("数据", "Silverlight.Common.View.DataGridDemo");
        }

        private void treeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

    //SilverLight学习笔记六TreeView控件中的TreeViewSample(TreeView控件)
            this.AddTabItem("树视图", "Silverlight.Common.View.TreeViewSample");
        }

        private void dataForm_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

    //SilverLight学习笔记七DataPager,DataForm控件的DataForm()
            this.AddTabItem("数据表单", "Silverlight.Common.View.DataFormDemo");
        }
    }
}