WPF:将多个视图绑定到 TabControl 的项目
在我们当前处理的项目中,我们有一个主窗口,其中包含多个视图(每个视图都有自己的视图模型),这些视图在选项卡控件中显示为项目。例如:一个选项卡项是编辑器,包含编辑器视图,如下所示:
<TabItem Header="Test Editor">
<TestEditor:TestEditorView DataContext="{Binding TestEditorViewModel}"/>
</TabItem>
另一个选项卡项显示结果:
<TabItem Header="Results Viewer">
<ResultViewer:ResultViewer x:Name="resultViewer1" DataContext="{Binding Path=ResultViewModel}" />
</TabItem>
等等
我希望将 TabItems 绑定到主窗口视图模型中的某些内容,但我不知道如何在不破坏 MVVM 模式的情况下将视图的名称绑定到任何属性。我想要这样的东西:
<TabControl.ContentTemplate>
<DataTemplate>
<TestEditor:TestEditorView DataContext ="{Binding TabDataContext}"/>
</DataTemplate>
</TabControl.ContentTemplate>
仅具有一些绑定,而不必在设计时知道将使用什么类型作为内容。
有什么想法吗?
In the current project we work on, we have a main window with several views (each with its own viewmodel) that are presented as items in a tab control. E.g: One tab item is an editor, and contains the editor view as follows:
<TabItem Header="Test Editor">
<TestEditor:TestEditorView DataContext="{Binding TestEditorViewModel}"/>
</TabItem>
Another one shows results:
<TabItem Header="Results Viewer">
<ResultViewer:ResultViewer x:Name="resultViewer1" DataContext="{Binding Path=ResultViewModel}" />
</TabItem>
etc.
I'd like to have the TabItems bound to something in the main window's viewmodel, but I can't figure out how to bind the view's name to any property without breaking the MVVM pattern. I'd like to have something like:
<TabControl.ContentTemplate>
<DataTemplate>
<TestEditor:TestEditorView DataContext ="{Binding TabDataContext}"/>
</DataTemplate>
</TabControl.ContentTemplate>
only with some binding instead of having to know at design time what type will be used as content.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常我将 TabControl 的选项卡与
SelectedIndex
一起存储在ViewModel
中,然后使用DataTemplates
来确定哪个View 显示
视图:
ViewModel:
Usually I have the TabControl's Tabs stored in the
ViewModel
, along with theSelectedIndex
, then I useDataTemplates
to determine whichView
to displayView:
ViewModel: