Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add user control in tab control in WPF

Tags:

c#

wpf

tabitem

The below article shows how to create dynamic tabs in WPF, that in each tab it will add just one text box.

private TabItem AddTabItem()
{
    int count = _tabItems.Count;

    // create new tab item
    TabItem tab = new TabItem();

    tab.Header = string.Format("Tab {0}", count);
    tab.Name = string.Format("tab{0}", count);
    tab.HeaderTemplate = tabDynamic.FindResource("TabHeader") as DataTemplate;

    tab.MouseDoubleClick += new MouseButtonEventHandler(tab_MouseDoubleClick);

    // add controls to tab item, this case I added just a textbox
    TextBox txt = new TextBox();

    txt.Name = "txt";
    tab.Content = txt;
    // insert tab item right before the last (+) tab item
    _tabItems.Insert(count - 1, tab);

    return tab;
}

http://www.codeproject.com/Articles/493538/Add-Remove-Tabs-Dynamically-in-WPF

what can I do for adding some complex controls that their positions are fixed instead of just 1 text box? can I create a user control for this purpose? so how can I add the user control to tab control?

like image 539
Elahe Avatar asked Apr 07 '16 05:04

Elahe


1 Answers

Try the next steps:

  1. Add a user control (Lets say in ComplexControl.xaml)

    <UserControl ... >
       <Grid>
           <Rectangle Width="100" Height="100" Fill="Red"/>
        </Grid>
     </UserControl> 
    
  2. Create a class

    Public myComplexContolClass
    {
         //....
    }
    
  3. Map them together so when you have a myComplexContolClass in your app visually it will be the UserControl from 1. The map can be done with DataTemplate:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        ...
                        xmlns:models="clr-namespace: ... .Model"
                        xmlns:views="clr-namespace: ... .View"
                        >
    
        <DataTemplate DataType="{x:Type models:myComplexContolClass}">
            <views:ComplexControl/>
        </DataTemplate>
    
    </ResourceDictionary>
    

Or

    <Window ...
            xmlns:models="clr-namespace: ... .Model"
            xmlns:views="clr-namespace: ... .View"
            >

        <Window.Resources>

            <DataTemplate DataType="{x:Type models:myComplexContolClass}">
                <views:ComplexControl/>
            </DataTemplate>

        </Window.Resources>

        // ...

    </Window>
  1. Add it to your code:

    private TabItem AddTabItem()
    {
        // ...
    
        myComplexContolClass control = new myComplexContolClass();
        tab.Content = control;
    
        // ...
    }
    
like image 180
Noam M Avatar answered Oct 26 '22 23:10

Noam M