Thursday, April 7, 2016

WPF - Add User Control Tabs in Tab Control.

We can add a Tab Item of TabControl dynamically.
This post is simple example that User Control Tabs is added in TabControl.

1. Add TabControl in Window.

2. Show a dialog of TabControl Items.

3. Remove a TabItem.

4. Create User Control.(I created 3 User Control)


5. Add Window Loaded event.

6. Type below code in Window Loaded event.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AddTabItem
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            UserControl[] userControls = new UserControl[] { new UserControl1(), new UserControl2(), new UserControl3()};
            foreach (UserControl uc in userControls)
            {
                TabItem tabItem = new TabItem();
                tabItem.Header = "New Tab";
                tabItem.Content = uc;

                tabControl1.Items.Add(tabItem);
            }
        }
    }
}

7. If you run WPF Appliction, you can see added 3 TabItem in TabControl.



2 comments: