简体   繁体   中英

WPF MVVM Multiple ContentControls in TabControl

I want my tabitem to display multiple usercontrols in a grid fashion. Imagine having a grid in a single tabitem where the first row and the second row contains corresponding usercontrol1 and usercontrol2 . ViewModels for these user controls are View1Model.cs and View2Model.cs .

I can currently display a single usercontrol using the following method:

Code for View.xaml :

<TabControl.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding Header}"/>
    </DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
    <DataTemplate>
        <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
            <ContentControl Content="{Binding Content}" />
        </ScrollViewer>
    </DataTemplate>
</TabControl.ContentTemplate>

Code for ViewModel.cs :

public ObservableCollection<TabItem> Tabs { get; set; }

public ToolViewModel ()
{
    Tabs = new ObservableCollection<TabItem>();
    Tabs.Add(new TabItem { Header = "Header", Content = new View1Model()});
}

Code for TabItem.cs (model):

public string Header { get; set; }
public ViewModelBase Content { get; set; }

Obviously, I can't add another one ContentControl to the same Header in this way. To solve the problem, I suppose I should firstly change public ViewModelBase Content { get; set; } public ViewModelBase Content { get; set; } public ViewModelBase Content { get; set; } to public ViewModelBase[] Content { get; set; } public ViewModelBase[] Content { get; set; } public ViewModelBase[] Content { get; set; } . However, I am not sure how I should display a list of ContentControl in xaml.

EDIT: I ended up using ObservableCollection<ViewModelBase> instead of simple arrays.

To solve the problem, I suppose I should firstly change public ViewModelBase Content { get; set; } public ViewModelBase Content { get; set; } public ViewModelBase Content { get; set; } to public ViewModelBase[] Content { get; set; } public ViewModelBase[] Content { get; set; } public ViewModelBase[] Content { get; set; } . However, I am not sure how I should display a list of ContentControl in xaml.

Use an ItemsControl :

<TabControl.ContentTemplate>
    <DataTemplate>
        <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
            <ItemsControl ItemsSource="{Binding Content}" />
        </ScrollViewer>
    </DataTemplate>
</TabControl.ContentTemplate>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM