Tabcontrol windows forms c

Последнее обновление: 31.10.2015

TabControl

Элемент TabControl позволяет создать элемент управления с несколькими вкладками. И каждая вкладка будет хранить некоторый набор других элементов управления,
как кнопки, текстовые поля и др. Каждая вкладка представлена классом TabPage.

Чтобы настроить вкладки элемента TabControl используем свойство TabPages. При переносе элемента TabControl с панели инструментов на форму
по умолчанию создаются две вкладки — tabPage1 и tabPage2. Изменим их отображение с помощью свойства TabPages:

Нам откроется окно редактирования/добавления и удаления вкладок:

Изменение вкладок

Каждая вкладка представляет своего рода панель, на которую мы можем добавить другие элементы управления,
а также заголовок, с помощью которого мы можем переключаться по вкладкам. Текст заголовка задается с помощью свойства Text.

Управление вкладками в коде

Для добавления новой вкладки нам надо ее создать и добавить в коллекцию tabControl1.TabPages с помощью метода Add:

//добавление вкладки
TabPage newTabPage = new TabPage();
newTabPage.Text = "Континенты";
tabControl1.TabPages.Add(newTabPage);

Удаление так же просто:

// удаление вкладки
// по индексу
tabControl1.TabPages.RemoveAt(0);
// по объекту
tabControl1.TabPages.Remove(newTabPage);

Получая в коллекции tabControl1.TabPages нужную вкладку по индексу, мы можем ей легко манипулировать:

// изменение свойств
tabControl1.TabPages[0].Text = "Первая вкладка";

SplitContainer

Элемент SplitContainer позволяет создавать две разделенные сплитером панели. Изменяя положение сплитера, можно изменить размеры этих панелей.

Элемент SplitContainer

Используя свойство Orientation, можно задать горизонтальное или вертикальное отображение сплитера на форму. В данном случае
это свойство принимает значения Horisontal и Vertical соответственно.

В случае, когда надо запретить изменение положения сплиттера, то можно присвоить свойству IsSplitterFixed значение true.
Таким образом, сплитер окажется фиксированным, и мы не сможем поменять его положение.

По умолчанию при растяжении формы или ее сужении также будет меняться размер обеих панелей сплитконтейнера. Однако мы можем закрепить за одной панелью
фиксированную ширину (при вертикальной ориентации сплиттера) или высоту (при горизонтальной ориентации сплиттера). Для этого нам надо установить у элемента
SplitContainer свойство FixedPanel. В качестве значения оно принимает панель, которую надо зафиксировать:

Чтобы изменить положение сплитера в коде, мы можем управлять свойством SplitterDistance, которое задает положение сплиттера в пикселях
от левого или верхнего края элемента SplitContainer. А с помощью свойства SplitterIncrement можно задать шаг, на который будет
перемещаться сплиттер при движении его с помощью клавиш-стрелок.

Чтобы скрыть одну из двух панелей, мы можем установить свойство Panel1Collapsed или Panel2Collapsed в
true

В приложении на Visual Studio можно реализовать такую особенность графического интерфейса взаимодействия с пользователем, как переключение между вкладками. В статье рассказывается, как это реализовать в рамках Windows Forms.

Переключение между вкладками — реализация

Сразу скажем, что для того, чтобы сделать в вашей программе переключение между вкладками, необходимо использовать элемент управления (контрол) tabControl. А теперь рассмотрим создание приложения подробно и по шагам.

Перво-наперво необходимо создать в среде разработки Visual Studio новый проект — Приложение Windows Forms. Язык программирование выбираете любой — тот, который вам нужен.

Создание проекта Windows Forms в Visual Studio

После этого из Панели элементов переносим на созданную Форму элемент управления tabControl (он находится в подгруппе Контейнеры).

Добавление элемента tabControl на Форму

Данный элемент управления на Форме выглядит следующим образом (мы растянули его по размеру Form1):

tabControl на Форме в Visual Studio

Теперь мы настроим tabControl: создадим нужное количество вкладок в нём, а также укажем их заголовки. Для того, чтобы это сделать, необходимо во вкладе Свойства данного элемента управления найти параметр TabPages и нажать кнопку с тремя точками около него.

Откроется окно «Редактор коллекции TabPage». Вы видите его на изображении ниже.

Редактор коллекции TabPage - Visual Studio

В нём с помощью кнопки «Добавить» можно добавлять вкладки. Название вкладки указывается в поле Text в правой части окна. Его, конечно же, можно поменять.

Мы добавили несколько вкладок на форму и изменили их названия. Посмотрите, что из этого получилось:

Переключение между вкладками - приложение на Visual Studio

На каждую из вкладок вы можете добавлять любые элементы управления — те, которые вам необходимы.

Вот так, легко и просто, реализовать переключение между вкладками в приложении на Visual Studio и Windows Forms!

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

The TabControl control (System.Windows.Forms.TabControl) allows you to create tabbed windows that you can see in many applications. An example of a tabbed window is the properties window of files and the tabs in Visual Studio.

Figure 1 – Tabs in Visual Studio

Figure 2 – Tabs in a Properties Window of a file

The TabControl serves as a container to other controls. You can access a tab by clicking it. The appearance of an active tab will change so you can distinguish which tab is activated. Once you click a tab, the controls that belong to it will be shown. The TabControl allows you to properly organize the a form into different tabs where each tab represents a category. For example, you can place a form that gets personal information on the Personal Info tab and the educational background in the Educational Background tab.

To add a tab control, go to the Containers category of the toolbox and find the TabControl. Drag it to the form. You can resize the control, but perhaps the best way is to use the Dock property so it will always take up the whole space of the form. You can go to the Properties window and find the Dock property. Click the drop down then click the middle button which means that the TabControl will be docked to all side of the form.

The TabControl consists of TabPage controls which represent the actual tab and its content. The tab pages of a tab control can be accessed using its TabPages property. The following are some useful methods of the TabPage control.

Property Description
Controls The controls that exist inside this TabPage.
ImageIndex Geting or seting the record showed up on this tab.
ImageKey Geting or seting the key accessor for the photograph in the ImageList of the associated TabControl.
Text The text that shows in the tab button of the TabPage.

Figure 3 – TabPage Properties

To add a tab page, you can click the small arrow button located at the upper right side of the TabControl. This will open the smart menu where you can add or remove tab pages.

Alternatively, you can go to properties window and find the TabPages property of the TabControl. Make sure that the TabControl is the control selected and not a TabPage. Click the button of the TabPages property to open the TabPages Collection Editor.

The TabPage Collection Editor allows you to add and remove tabs and change properties such as the text of individual tabs. You can add controls to individual containers of the tab. For example, drag some controls to the body of the first tab. Then you can click on the second tab in the Designer and you can add another set of controls for that tab.

Let us now discuss the TabControl itself. The following are some properties of the TabControl.

Property Description
Alignment The area (top, bottom, left, right) where the tabs are aligned. The default is top.
Appearance The appearance of the control’s tabs.
ImageList Contains a list of images that will be displayed for each tab.
ItemSize Specifies the size of the tab.
Multiline Allows you to create multiple rows of tabs.
SelectedIndex Specifies the index of the selected tab page.
SelectedTab Gets or sets the selected tab.
TabCount Returns the number of TabPages of the TabControl.
TabPages Allows you to access the tab pages of the TabControl and add or remove tab pages.

Figure 4 – TabControl properties

The Alignment property specifies where the tabs are located. The default value is Top which displays the tab in the top of the TabControl. The Appearance property changes the appearance of the tabs. It can accept three values such as Normal (the default), Buttons (which makes the tab look like a button), or FlatButtons (buttons that are not popping out). Figure 4 shows the appearance of the tab using different values for the Appearance property.

Figure 4 – TabControl Appearances

The ImageList Property allows you to add image icons to each tab. This property accepts a reference to an ImageList control. The ImageList control is commonly used for this property which is also available in other controls such as menus and tree views. We will discuss briefly here how to use the ImageList to provide images to other control, in this case, the TabControl. Drag an ImageList from the toolbox to the form. It is located in the Components section of the Toolbox. The ImageList will then be located in the component tray of the Designer. The ImageList will use the following two images:

Save it to any location in your hard drive. Now click the ImageList control located in the component tray of the Designer. Find the Images property in the Properties Window and click the button beside it. You will be presented with the Image Collection Editor.

Clicking the Add button allows you to browse for an image. Add the two images I have provided then click OK. You must now assign the image list to the ImageList property of the TabControl. Go to the ImageList property of the TabControl and choose the image list we have created. To show this icon beside the tabs of the TabControl, select the individual tab page in the designer (by clicking its body) then go to the Properties Window and find the ImageIndex property. Clicking the dropdown beside it will show you the indexes and a preview of each image. Assign your desired index to each tab. You can use the same index for different tabs. Your tabs will now show images beside their text.

You can adjust the ItemSize property to adjust the size of tabs. This is useful when the images you placed in tabs are too big.

If the number of tabs is too many and it doesn’t fit the width of the form, then arrow buttons will show up to the top right of the TabControl next to the last visible tab.

You can click the arrows to scroll the tabs to the left or to the right.

The MultiLine property allows you to create multiple columns of tabs. If the tabs are too many, then you can set this property to true.

The TabPages property allows you to add or remove tab pages to the TabControl. The following code programmatically adds three more tab pages to the TabControl.

TabPage tab1 = new TabPage("Tab 1");
TabPage tab2 = new TabPage("Tab 2");
TabPage tab3 = new TabPage("Tab 3");
tabControl1.TabPages.Add(tab1);
tabControl1.TabPages.Add(tab2);
tabControl1.TabPages.Add(tab3);

The TabPages has a type of TabPageCollection which is a collection of TabPage objects. Therefore, we can use typicall collection methods such as AddRemove, or AddRange.

You can use the SelectedIndex property to get the index of the selected tab. The index is the position of the selected tab in the TabPages collection.

MessageBox.Show("The selected tab is " + tabControl1.TabPages[tabControl1.SelectedIndex].Text);

The SelectedTab simply returns or sets the selected TabPage object.

TabPage selectedTab = tabControl1.SelectedTab;
MessageBox.Show("The selected tab is " + selectedTab.Text);

The TabCount simply returns the number of TabPages of the TabControl.

The TabControl has a SelectedIndexChanged event which triggers when the selected tab changes.

The TabControl is very useful when your form has different sections or categories. A good example where a TabControl will be useful is in a Form that provides the options or settings of an application.

Время на прочтение6 мин

Количество просмотров5.9K

Случилось недавно так, что понадобилось в одном проекте использовать компонент TabControl. Стандартный компонент, ничего необычного, достаточно удобный. Нюанс заключался в том, что нужно было использовать свой тип вкладок на основе перегруженного TabPage. Кроме этого, необходимо было позволить пользователю добавлять вкладки самому в процессе работы. Выглядеть оно должно было примерно так:

Радует, что стандартные компоненты позволяют делать с ними достаточно много извращений.

Линк на тестовый проект с примером. Под

2011

2010 студию.

Начнем с кастомного типа вкладок.
К сожалению, TabControl, в отличие от DataGridViewColumn, не позволяет указывать тип вложенного элемента через внутреннюю переменную. Так это делается в DataGridViewColumn:


        public class CustomDataGridViewColumn : DataGridViewTextBoxColumn
        {
            public CustomDataGridViewColumn()
            {
                this->CellTemplate = CustomDataGridViewCell;
            }
        }

Проект должен быть изменен под Net 4 Full profile, т.к. нужно подключать две сборки — System.Design и System.Drawing.Design.

Увы, сделать аналогично в TabControl не получится, придется переопределять тип TabPageCollection, объявленный внутри TabControl. Итак, объявляем сам класс и необходимые методы, далее разберем по очереди. Да, и сразу предупрежу — внутри файла с кодом не было строчки «using System.Windows.Forms;», поэтому обращение к стандартным компонентам в коде примера идет с приставкой «System.Windows.Forms.». А TabControl и TabPage это кастомные переопределенные типы.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Drawing.Design;
using System.ComponentModel.Design;

namespace WindowsFormsApplication1
{
    public class TabControl : System.Windows.Forms.TabControl
    {
        //Объявляем новый тип коллекции вкладок. 
        public new class TabPageCollection : System.Windows.Forms.TabControl.TabPageCollection
        {
            public TabPageCollection(TabControl owner)
                : base(owner)
            {

            }
        }

        public TabControl()
        {

        }

        private TabPageCollection mTabCollection = null;

        //Переопределяем свойство для доступа к коллекции вкладок, указывая в атрибуте Editor тип редактора коллекции.
        [Editor(typeof(TabPageCollectionEditor), typeof(UITypeEditor))]
        public new System.Windows.Forms.TabControl.TabPageCollection TabPages
        {
            get
            {
                if (mTabCollection == null) mTabCollection = new TabPageCollection(this);
                return mTabCollection;
            }
        }
    }

    //Редактор коллекции вкладок тоже пришлось переопределять. В нем всего два перегруженных метода.
    public class TabPageCollectionEditor : System.ComponentModel.Design.CollectionEditor
    {
        public TabPageCollectionEditor(Type type)
            : base(type)
        {

        }

        protected override Type CreateCollectionItemType()
        {
            return typeof(TabPage);
        }

        protected override Type[] CreateNewItemTypes()
        {
            return new Type[] { typeof(TabPage) };
        }
    }
}

И простенький TabPage:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication1
{
    public class TabPage : System.Windows.Forms.TabPage
    {
        public TabPage()
        {

        }
    }
}

Думаю, тут все понятно. Переходим к следующему этапу.

Добавление вкладок пользователем.
Для обеспечения этой возможности мы пошли самым простым путем: в TabControl постоянно присутствует дополнительная пустая вкладка с заголовком «+». При её нажатии генерируется событие добавления вкладки.

Во-первых, в типе TabPageCollection перегружаем метод Clear — при очищении вкладок нам НЕ надо удалять вкладку «+».


            public override void Clear()
            {
                System.Windows.Forms.TabPage page = null;
                if (this.ContainsKey(TabControl.KeyPageAllowAddName)) page = this[TabControl.KeyPageAllowAddName];

                base.Clear();

                if (page != null) this.Add(page);
            }

В коде TabControl объявляем переменную, которая хранит имя вкладки «+».


        public static string KeyPageAllowAddName = "___page_allow_to_add_name___";

Объявляем свойство AllowUserToAddTab компонента для того чтобы можно было включать/отключать новый режим работы. Ну и собственно метод, проверяющий наличие такой вкладки и в случае необходимости добавляющий/удаляющий её.


        public TabControl()
        {
            this.Enter += new EventHandler((sender, e) => { CheckAllowUserToAddTab(); });
            this.Selecting += new System.Windows.Forms.TabControlCancelEventHandler(TabControl_Selecting);
        }

        private bool mAllowUserToAddTab = false;
        [Browsable(true), Description("Позволяет пользователю добавлять вкладки. Добавляется элемент +, по щелчку на который создается событие OnUserAddedTab."), Category("Action")]
        public virtual bool AllowUserToAddTab
        {
            get { return mAllowUserToAddTab; }
            set { mAllowUserToAddTab = value; }
        }

       void CheckAllowUserToAddTab()
        {
            if (mAllowUserToAddTab)
            {
                System.Windows.Forms.TabPage page_allow_to_add = TabPages[KeyPageAllowAddName];

                if (mAllowUserToAddTab)
                {
                    if (page_allow_to_add == null)
                    {
                        page_allow_to_add = new TabPage();
                        page_allow_to_add.Name = KeyPageAllowAddName;
                        page_allow_to_add.Text = "+";
                        TabPages.Insert(0, page_allow_to_add);
                    }
                }
                else
                {
                    if (page_allow_to_add != null) TabPages.Remove(page_allow_to_add);
                }
            }
        }

Описываем делегат для события добавления вкладки:


    public delegate bool TabPageAdding(TabControl control, TabPage page);

Событие и метод для добавления вкладки:


        public event TabPageAdding PageAdding;
        void TabControl_Selecting(object sender, System.Windows.Forms.TabControlCancelEventArgs e)
        {
            if (TabPages.Count > 0 && e.TabPage.Name == KeyPageAllowAddName)
            {
                e.Cancel = true;

                TabPage page = new TabPage();
                if (PageAdding != null)
                    foreach (TabPageAdding _delegate in PageAdding.GetInvocationList())
                    {
                        try
                        {
                            if (!_delegate.Invoke(this, page)) return;
                        }
                        catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); }
                    }

                TabPages.Add(page);
            }
        }

Перебирается список всех подписчиков на событие добавления, если хоть один из них вернет False — добавление отменяется.

В классе TabPageCollectionEditor надо перегрузить методы GetItems и SetItems. Они нужны для передачи массива вкладок из редактора в компонент и обратно, при этом надо исключать вкладку «+».


        protected override object[] GetItems(object editValue)
        {
            try
            {
                object[] values = base.GetItems(editValue);
                List<object> values2 = new List<object>();
                foreach (var element in values)
                {
                    if (element.GetType() == typeof(TabPage))
                    {
                        TabPage tp = (TabPage)element;
                        if (tp.Name == TabControl.KeyPageAllowAddName) continue;
                    }
                    values2.Add(element);
                }
                return values2.ToArray();
            }
            catch (Exception ex){System.Windows.Forms.MessageBox.Show(ex.Message);}
            return base.GetItems(editValue);
        }

        protected override object SetItems(object editValue, object[] value)
        {
            try
            {
                List<object> values2 = new List<object>();
                foreach (var element in value)
                {
                    if (element.GetType() == typeof(TabPage))
                    {
                        TabPage tp = (TabPage)element;
                        if (tp.Name == TabControl.KeyPageAllowAddName) continue;
                    }
                    values2.Add(element);
                }
                return base.SetItems(editValue, values2.ToArray());
            }
            catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); }
            return base.SetItems(editValue, value);
        }

Далее добавили еще одну возможность: отслеживание первого открытия вкладки (по первому заходу на вкладку инициализировались формочки)

Тут добавляется еще одно событие, список и обработчик событий SelectedIndexChanged/Enter/Click:


        public TabControl()
        {
            this.Enter += new EventHandler(TabControl_PageEvent);
            this.Click += new EventHandler(TabControl_PageEvent);
            this.SelectedIndexChanged += new EventHandler(TabControl_PageEvent);

            this.Enter += new EventHandler((sender, e) => { CheckAllowUserToAddTab(); });
            this.Selecting += new System.Windows.Forms.TabControlCancelEventHandler(TabControl_Selecting);
        }

        ....

        private Dictionary<System.Windows.Forms.TabPage, bool> mLoaded = new Dictionary<System.Windows.Forms.TabPage, bool>();
        public delegate void TabPageLoadedEventHandler(TabControl control, System.Windows.Forms.TabPage page);
        public event TabPageLoadedEventHandler PageLoad;
        void TabControl_PageEvent(object sender, EventArgs e)
        {
                if (this.SelectedTab != null && !mLoaded.ContainsKey(this.SelectedTab))
                {
                    mLoaded.Add(this.SelectedTab, true);
                    if (PageLoad != null) PageLoad(this, this.SelectedTab);
                }
        }

Конечно, дорабатывать тут еще можно много чего — например, в TabPageControlCollection перегружать методы для более точного определения номера вкладки (чтобы исключать вкладку «+»).
К сожалению, я не нашел способа реализовать функциональность вкладки «+» через перегрузку методов отрисовки компонента, так что не обессудьте за кривой способ. Имхо как альтернатива установке DevExpress, например — сойдет.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Microsoft antivirus essential для windows 7 x64
  • Windows 10 home настройка удаленного доступа
  • Microsoft windows kernel general
  • Увеличительное стекло для windows
  • Можно ли установить блютуз на компьютер windows 10