包含使用 MVVM 的不同用户控件的 TabControls [英] TabControls containing different user controls using MVVM
问题描述
我正在按照 MVVM 制作 WPF 应用程序.我希望在我的应用程序中有一个包含一些常用按钮和文本框以及一个 TabControl
的视图.TabControl 将基本上托管不同的 UserControls
.因此,对于每个 UserControl
,我都准备了一个单独的 View
和一个 ViewModel
.
I am making a WPF application following MVVM. What I want in my application is that there is a View which contains some common buttons and text boxes and a TabControl
. TabControl will basically host different UserControls
. So for each UserControl
I have a separate View
and a ViewModel
ready.
我的应用程序的结构如下所示.
So structure of my application looks like this.
MainWindow.Xaml
EntryView.Xaml
Button1
Button2
TabControl
UserControl1 (View)
UserControl2 (View)
UserControl3 (View)
儿子在我的 EntryView 中有选项卡控件.现在我需要绑定这个.
Son in my EntryView I have the tab control. Now I need to bind this.
这是我所做的.
EntryView.Xaml
<TabControl ItemsSource="{Binding Tabs}" SelectedItem="{Binding SelectedTab}">
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type vm:UserControl1ViewModel}">
<v:UserControl1View/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:UserControl2ViewModel}">
<v:UserControl2View/>
</DataTemplate>
</TabControl.ContentTemplate>
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="Header"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
EntryViewModel.cs
private ObservableCollection<BaseViewModel> _tabs;
public ObservableCollection<BaseViewModel> Tabs
{
get
{
if (_tabs == null)
{
_tabs = new ObservableCollection<BaseViewModel>();
_tabs.Add(new UserControl1ViewModel());
_tabs.Add(new UserControl2ViewModel());
}
return _tabs;
}
}
但是现在当我运行我的应用程序时什么也没有发生.TabControl 为空.我在视图模型的 Tabs 中放置了断点,但它没有被击中.所以问题一是我这样做对吗?如果没有,那我该怎么办?
But now when I run my application nothings happens. TabControl is empty. I put breakpoint inside Tabs in view model, but it didn't get hit. So question one is am I doing this right? If no then what should I do?
推荐答案
对于初学者,我不知道它如何在您的机器上编译,因为在我的机器上它给了我这个错误:
For starters I don't know how it compiles on your machine as on my machine it gives me this error:
属性ContentTemplate"只能设置一次.
The property "ContentTemplate" can only be set once.
但是,当我将 DataTemplates
移动到 TabControl.Resources
时,它可以编译并正常工作:
However when I move DataTemplates
to TabControl.Resources
it compiles and works fine:
<TabControl>
<TabControl.Resources>
<DataTemplate DataType="{x:Type vm:UserControl1ViewModel}">
<v:UserControl1View/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:UserControl2ViewModel}">
<v:UserControl2View/>
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="Header"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
这篇关于包含使用 MVVM 的不同用户控件的 TabControls的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!