我有一个名为TabViewModel的类,它具有Name等属性。
我需要能够动态添加标签,每当添加新标签时,我都需要创建一个新的TabViewModel实例并将其绑定到新标签页。
这是我的代码:
XAML:
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
代码背后: 添加新标签时..
_tabItems = new List<TabItem>();
tabItem.DataContext = ViewModel.CreateNewTabViewModel();
_tabItems.Add(tabItem);
TabControl1.ItemsSource = _tabItems;
TabControl1.SelectedIndex = 0;
因此,CreateNewTabViewModel假设创建一个新的TabViewModel并将Name属性设置为显示在选项卡标题上,这就是TextBlock与Name绑定的原因。
我也尝试了tabItem.SetBinding,但它没有用。
请建议。
谢谢!
答案 0 :(得分:1)
_tabItems = new List<TabItem>();
//...
_tabItems.Add(tabItem);
TabControl1.ItemsSource = _tabItems;
使用仅包含单个标签项的新列表替换整个标签项列表。
那就是说,代码不清楚它在做什么,似乎很多都不需要。这有效:
var tabItems = new List<TabViewModel>();
tabItems.Add(new TabViewModel { Name = "MyFirstTab" });
myTabControl.ItemsSource = tabItems;
myTabControl.SelectedIndex = 0;
您需要做的就是将视图模型的实例添加到视图模型列表中,并指向选项卡控件以使用它。无需设置数据上下文;通过设置项目源,您隐式将每个选项卡的datacontext设置为集合中的项目。