I have the a tabcontrol in my MainWindow. The default/first tab of the tabcontrol is the home user control. In the home page I have a button that can add further tabs.
MainWindow.xaml:
<Window.Resources>
<DataTemplate x:Key="ClosableTabItemTemplate">
<Button Content="X" Cursor="Hand" DockPanel.Dock="Right" Focusable="False"
FontFamily="Courier" FontSize="9" FontWeight="Bold" Margin="0,1,0,0" Padding="0"
VerticalContentAlignment="Bottom" Width="16" Height="16"/>
</DataTemplate>
</Window.Resources>
<Grid>
<TabControl Name="tabMain" ItemsSource="{Binding TabItems,UpdateSourceTrigger=PropertyChanged}" />
</Grid>
In my view model I have the add functionality where a new tab has been added. I need the close button for all these newly added tabs.
public MainViewModel()
{
try
{
Home Item2 = new Home();
TabItems.Add(new TabItem() { Header = "Home", Content = Item2 });
}
catch(Exception ex)
{
MessageBox.Show("Exception "+ex);
}
//Function to add new tabs.
public void AddNewTabs()
{
ChildWindow childContent = new ChildWindow();
TabItem item = new TabItem() { Header = "New Tab", Content = childContent};
item.MouseDoubleClick += new MouseButtonEventHandler(tab_MouseDoubleClick);
TabItems.Add(item);
}
Right now new tabs are being added but without the close button. I have tried giving
item.HeaderTemplate = FindResource("ClosableTabItemTemplate") as DataTemplate;
But it shows error.
Any help would be appreciated.
Thanks in advance.