WPF TabControl with ContentControl
I searched a lot on SO and didn't find an answer to my problems. I want to use TabControl with MVVM. This is how I add TabControl to MainWindow.xaml
<Window.Resources>
<DataTemplate DataType="{x:Type models:PartnersViewModel}">
<views:PartnersView />
</DataTemplate>
<DataTemplate DataType="{x:Type models:ProjectsViewModel}">
<views:ProjectsView />
</DataTemplate>
</Window.Resources>
<Window.DataContext>
<models:ApplicationViewModel/>
</Window.DataContext>
<TabControl ItemsSource="{Binding PageViewModels}" TabStripPlacement="Left">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentControl Content="{Binding}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
PageViewModels - ObservableCollection<IPageViewModel>
.
IPageViewModel
- simple interface with one property Name
. There are 2 implementations of this interface PartnersViewModel
and ProjectsViewModel
.
public class ProjectsViewModel : IPageViewModel
{
public String Name
{
get { return "Projects"; }
}
}
public class PartnersViewModel : IPageViewModel
{
public String Name
{
get { return "Partners"; }
}
}
I want each tab to appear as ContentControl. The title text is taken from the Name property. My ProjectView and PartnersView looks like this:
<UserControl x:Class="WANIRPartners.Views.ProjectsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" >
<Grid>
<Label Content="Projects Content" />
</Grid>
</UserControl>
Using this code, the title and content are TabControl
exactly the same. Content / Partner Content appears in tab headers as well (this is normal) in tab content. When I change <Label/>
to <DataGrid/>
, the table headers contain datagrid (sic!). How can I get this to work as expected. I mean, how can I display the titles as property value Name
and the contents of the tab as displayable correctly <views:PartnersView />
or <views:ProjectsView />
whichever is in PageViewModels
.
source to share
your code should work, doesn't have IDE atm. you can also use Snoop to check bindings at runtime. i changed ContentTemplate to:
<TabControl.ContentTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding .}" />
</DataTemplate>
</TabControl.ContentTemplate>
and it works. but even your code works in my testapp.
source to share