WPF TabControl 数据绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/686074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF TabControl Databinding
提问by mackenir
I'm trying to build a WPF user interface containing a TabControl, and a TextBlock.
我正在尝试构建一个包含 TabControl 和 TextBlock 的 WPF 用户界面。
I want to bind these two controls to an underlying collection of instances of the following class:
我想将这两个控件绑定到以下类的基础实例集合:
class PageModel
{
public string Title {get;set;}
public string TabCaption {get;set;}
public FrameworkElement TabContent {get;set}
}
The tab control should display a tab for each PageModel.
选项卡控件应该为每个 PageModel 显示一个选项卡。
- Each tab's header should display the TabCaption property
- Each tab's content should be the TabContent property.
- 每个选项卡的标题应显示 TabCaption 属性
- 每个选项卡的内容应该是 TabContent 属性。
The TextBlock should display the Title of the currently selected tab.
TextBlock 应显示当前选定选项卡的标题。
How can I achieve this result?
我怎样才能达到这个结果?
回答by Kent Boogaart
<TabControl x:Name="_tabControl" ItemsSource="{Binding PageModels}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding TabCaption}"/>
<Setter Property="Content" Value="{Binding TabContent}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
<TextBlock Text="{Binding SelectedItem.Title, ElementName=_tabControl}"/>
回答by sfaust
I also found another solution to this hereusing ItemTemplate and ContentTemplate.
我还在这里使用 ItemTemplate 和 ContentTemplate找到了另一个解决方案。
Also for any WPF newbies like me, after some headaches and frustration I realized that the collection of page models needs to be an ObservableCollection<PageModel>
instead of a List<PageModel>
or any changes to the list will not be reflected by the tabs (i.e. you can't add or remove a tab if it's a list).
同样对于像我这样的任何 WPF 新手,在经历了一些头痛和挫折之后,我意识到页面模型的集合需要是一个ObservableCollection<PageModel>
而不是一个,List<PageModel>
否则列表的任何更改都不会反映在选项卡上(即您不能添加或删除如果是列表,则为选项卡)。