Dhinnesh Jeevan
Dhinnesh Jeevan

Reputation: 549

How to bind a class to a TabItem DataContext in code-behind

I have a class called TabViewModel, and it has properties like Name, etc..

I need to be able to add tabs dynamically, and whenever a new tab is added, I need create a new instance of the TabViewModel and bind it to the new tab.

Here's my code:

XAML:

            <TabControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </TabControl.ItemTemplate>

Code behind: When adding a new tab..

_tabItems = new List<TabItem>();    
tabItem.DataContext = ViewModel.CreateNewTabViewModel();    
_tabItems.Add(tabItem);    
TabControl1.ItemsSource = _tabItems;    
TabControl1.SelectedIndex = 0;

So, CreateNewTabViewModel is suppose to create a new TabViewModel and set the Name property to be displayed on the tab header, which is why the TextBlock is bounded to Name.

I also tried tabItem.SetBinding but it didn't work.

Please advice.

Thanks!

Upvotes: 0

Views: 749

Answers (1)

Emond
Emond

Reputation: 50672

_tabItems = new List<TabItem>();    
//...
_tabItems.Add(tabItem);    
TabControl1.ItemsSource = _tabItems;      

Replaces the entire list of tab items with a new list that contains just a single tab item.

That said, the code is not quite clear on what it is doing, a lot seem unneeded. This works:

var tabItems = new List<TabViewModel>();
tabItems.Add(new TabViewModel { Name = "MyFirstTab" });
myTabControl.ItemsSource = tabItems;
myTabControl.SelectedIndex = 0;

All you need to do is add an instance of a view model to a list of view models and point the tab control to use it. There is no need to set the data context; by setting the items source you are implicitly setting the datacontext of each tab to an item in the collection.

Upvotes: 1

Related Questions