简体   繁体   English

如何在WPF中的选项卡控件中添加用户控件

[英]How to add user control in tab control in WPF

The below article shows how to create dynamic tabs in WPF, that in each tab it will add just one text box. 下面的文章展示了如何在WPF中创建动态选项卡,在每个选项卡中它将只添加一个文本框。

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 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? 我可以做些什么来添加一些复杂的控件,他们的位置是固定的,而不是只有1个文本框? can I create a user control for this purpose? 我可以为此目的创建用户控件吗? so how can I add the user control to tab control? 那么如何将用户控件添加到选项卡控件?

Try the next steps: 尝试以下步骤:

  1. Add a user control (Lets say in ComplexControl.xaml) 添加用户控件(让我们说在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: 将它们映射在一起,这样当你的应用程序中有一个myComplexContolClass时,它将是来自1的UserControl。可以使用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; // ... } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM