0

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 control?

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.

H.B.
  • 166,899
  • 29
  • 327
  • 400
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

2 Answers2

1

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.

TalentTuner
  • 17,262
  • 5
  • 38
  • 63
0

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465