开发者

Implement open a new tab

how can i, in C#/WPF implement an application where i can open/close a new tab? i am thinking i will have to create a "template" user control and programmatically, create a new instance of the control (tab item) and add it into the tab contr开发者_高级运维ol?

i am new to C#/WPF so how can i get started with this?

another thing is how can i modify or access child controls when i dont have an ID.


You can do this very eaisly with ObservableCollections.

xaml

    <TabControl ItemsSource="{Binding EmpList }">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding FirstName }"></TextBlock>
            </DataTemplate>
        </TabControl.ItemTemplate>
    </TabControl>

Code Asumeing you are using MVVM

Create a EmpList Observablecollection in your ViewModel

so when you add a new object in Observablecollection , tab control listen for the change and add new tab for you.


This is the code that I used.

    private void addtabbutton_Click(object sender, RoutedEventArgs e)
    {
        // We use tabItem1 and codebox as template<typename T> for the new objects.
        var tabitem = new System.Windows.Controls.TabItem();
        tabitem.ContextMenu = tabItem1.ContextMenu;
        tabitem.ContextMenuClosing += tabItem1_ContextMenuClosing;
        tabitem.ContextMenuOpening += tabItem1_ContextMenuOpening;
        tabitem.Header = "Code" + NewTabItemIndex.ToString();
        tabitem.Height = tabItem1.Height;
        tabitem.Width = tabItem1.Width;
        tabitem.HorizontalAlignment = tabItem1.HorizontalAlignment;
        tabitem.VerticalAlignment = tabItem1.VerticalAlignment;
        tabitem.DataContext = tabItem1.DataContext;
        var textbox = new System.Windows.Controls.TextBox();
        tabitem.Content = textbox;
        textbox.DataContext = codebox.DataContext;
        textbox.LayoutTransform = codebox.LayoutTransform;
        textbox.AcceptsReturn = true;
        textbox.AcceptsTab = true;
        textbox.Height = this.codebox.Height;
        textbox.HorizontalAlignment = codebox.HorizontalAlignment;
        textbox.VerticalAlignment = codebox.VerticalAlignment;
        NewTabItemIndex++;
        this.tabControl1.Items.Add(tabitem);
    }

You can see that I started off with one tab item, tabItem1, in the box. Then I essentially copy it's characteristics into a new TabItem. Then I add that TabItem into my TabControl.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜