tabcontrol 动态添加用户页面

动态添加用户控件并选择最后一次添加的页面

 1   <TabControl ItemsSource="{Binding TabItems}"  SelectedItem="{Binding SelectedTabItem}" >
 2       <!-- ItemTemplate定义选项卡头(Header)的显示 -->
 3       <TabControl.ItemTemplate>
 4           <DataTemplate>
 5               <TextBlock Text="{Binding Title}"/>
 6               <!-- 绑定到你的标题属性 -->
 7           </DataTemplate>
 8       </TabControl.ItemTemplate>
 9       <!-- ContentTemplate定义选项卡内容的显示 -->
10       <TabControl.ContentTemplate>
11           <DataTemplate>
12               <ContentControl Content="{Binding Content}"/>
13               <!-- 绑定到你的内容属性 -->
14           </DataTemplate>
15       </TabControl.ContentTemplate>
16   </TabControl>

ViewModel代码

 1    public RelayCommand  AddNnewTabCoommand { get; }
 2    //实例化命令
 3     AddNnewTabCoommand = new RelayCommand(AddNewTab);
 4    int Index = 0;
 5    public void AddNewTab()
 6    {
 7        // 创建新的用户控件实例
 8        UserControl userControl = new UserControl1();
 9        // 创建TabItem并设置其内容
10        TabItem newTabItem = new TabItem();
11        Index++;
12        newTabItem.Header = "动态页面" + Index.ToString();
13        //newTabItem.Content = "动态页面" + Index.ToString() + Index.ToString();
14     
15        newTabItem.Content = userControl;
16        //newTabItem.Focus();
17        
18        // 添加到集合,界面会自动更新
19        TabItems.Add(newTabItem);
20        // 关键:添加后立即将新选项卡设置为选中状态
21        SelectedTabItem = newTabItem;
22 
23    }
24    private object _selectedTabItem;
25    public object SelectedTabItem
26    {
27        get => _selectedTabItem;
28        set
29        {
30            _selectedTabItem = value;
31            OnPropertyChanged(nameof(SelectedTabItem));
32        }
33    }

 

posted @ 2025-11-28 14:55  家煜宝宝  阅读(4)  评论(0)    收藏  举报