简体   繁体   English

如何在代码隐藏中将类绑定到TabItem DataContext

[英]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.. 我有一个名为TabViewModel的类,它具有诸如Name等的属性。

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. 我需要能够动态添加选项卡,并且每当添加新选项卡时,都需要创建TabViewModel的新实例并将其绑定到新选项卡。

Here's my code: 这是我的代码:

XAML: 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. 因此,假设CreateNewTabViewModel创建一个新的TabViewModel并将Name属性设置为显示在选项卡标题上,这就是TextBlock绑定到Name的原因。

I also tried tabItem.SetBinding but it didn't work. 我也尝试了tabItem.SetBinding,但是没有用。

Please advice. 请指教。

Thanks! 谢谢!

_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. 通过设置项目源,可以隐式地将每个选项卡的数据上下文设置为集合中的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM