I’m trying to add a new TabItem to TabControl each time I click on a button and I have no problem with that. But I want a textbox inside each TabItem. How do I do that? I need to do that with code I suppose.
TabItem newTab = new TabItem();
newTab.Header = ncn.courseName;
newTab.FontSize = 20;
TextBox textbox = new TextBox();
textbox.Width = 200;
textbox.Height = 100;
textbox.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
textbox.VerticalAlignment = System.Windows.VerticalAlignment.Top;
Grid grid = new Grid();
grid.Children.Add(textbox);
newTab.Content = grid;
this.Courses.Items.Add(newTab);
this.Courses.SelectedItem = newTab;
If you would like to use only code and not the MVVM pattern, this can be solved this way:
That is solving it “the old way” by using code-behind.
If you on the other want to use the WPF like it should, you can do like this.
To simplify a bit, I am using the code-behind as DataContext. I would recommend using a class instead in the running code.
I have also used the Cutton click event instead if using the Button Command.
First I create a “holder” class for the tab items, holding the data you need.
TabItemHolder.cs
Then I have the model class, in this example the MainWindow.cs itself:
MainWindow.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
public static readonly DependencyProperty SelectedTabProperty = DependencyProperty.Register(“SelectedTab”, typeof(TabItemHolder), typeof(MainWindow), new UIPropertyMetadata());
public TabItemHolder SelectedTab
{
get { return (TabItemHolder)GetValue(SelectedTabProperty); }
set
{
SetValue(SelectedTabProperty, value);
NotifyPropertyChanged(“SelectedTab”);
}
}
}
And finally, the XAML would be something like this.
MainWindow.xaml
That would do the same trick in a different (and in my opinion better) way.
I hope that helps you.