TabControls包含使用MVVM的不同用户控件

本文关键字:用户 控件 包含使 MVVM TabControls | 更新日期: 2023-09-27 18:18:05

我正在制作MVVM以下的WPF应用程序。我想在我的应用程序是有一个视图,其中包含一些常见的按钮和文本框和TabControl。TabControl基本上会托管不同的UserControls。因此,对于每个UserControl,我都准备了一个单独的ViewViewModel

程序的结构是这样的

MainWindow.Xaml
    EntryView.Xaml
        Button1
        Button2
        TabControl
            UserControl1 (View)
            UserControl2 (View)
            UserControl3 (View)

儿子在我的EntryView我有标签控件。现在我需要绑定这个

这是我所做的。

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为空。我把断点放在视图模型的标签中,但它没有被击中。第一个问题是,我这样做对吗?如果没有,我该怎么办?

TabControls包含使用MVVM的不同用户控件

对于初学者,我不知道它是如何在你的机器上编译的,因为在我的机器上它给了我这个错误:

属性"ContentTemplate"只能设置一次。

然而,当我将DataTemplates移动到TabControl.Resources时,它编译并工作良好:

<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>

真正的罪魁祸首是

<TabControl.ContentTemplate>

只接受一个DataTemplate元素作为内容。该属性不能设置两次。

为TabControl(或窗口)资源中的每种类型指定一个DataTemplate就可以了。

理想情况下,在我看来,你只需要添加UserControlViews到你的ItemsSource和视图可以设置自己的DataContext到ViewModels.