0
votes

I am workign on MVVM, and i have Main View in which i have a tabcontrol and 3 tabitems. Now on click to each tabitems i want to display a new view. (I have three Views).

My try to do that is :

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm1="clr-namespace:WpfApplication1"
        xmlns:vm2="clr-namespace:WpfApplication1"
        xmlns:vm3="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <vm1:View1 x:Key="View1Display1"></vm1:View1>
        <vm2:View2 x:Key="ViewDisplay2"></vm2:View2>
        <vm3:View3 x:Key="ViewDisplay3"></vm3:View3>
    </Window.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <TabControl Background="Green">
            <TabItem Height="20" Width="100" Header="Tab1" DataContext="{Binding Path=View1Display1}"></TabItem>
            <TabItem Height="20" Width="100" Header="Tab2" DataContext="{Binding Path=View1Display2}"></TabItem>
            <TabItem Height="20" Width="100" Header="Tab3" DataContext="{Binding Path=View1Display3}"></TabItem>
        </TabControl>          
    </Grid>
</Window>

Where View1 is : (Similar is View2 and View3)

<UserControl x:Class="WpfApplication1.View1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock  VerticalAlignment="Center" HorizontalAlignment="Center">I am from View1</TextBlock>
    </Grid>
</UserControl>

MainWindow.xaml.cs is :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new  ViewModel();
    }        
}

This is ViewModel:

class ViewModel
{
    public ViewModel()
    {
    }
}

Why TabItem do not show the respective views on clicking to them even i have set datacontext corresponding to their View.

1

1 Answers

1
votes

Instead of binding the DataContext on each TabItem, you need to bind the Content, and then you can bind each TabItem to an instance of its ViewModel, of Do that in the UserControls them selfs

 <TabControl Background="Green">
        <TabItem Height="20" Width="100" Header="Tab1" Content="{StaticResource View1Display1}"></TabItem>
        <TabItem Height="20" Width="100" Header="Tab2" Content="{StaticResource ViewDisplay2}"></TabItem>
        <TabItem Height="20" Width="100" Header="Tab3" Content="{StaticResource ViewDisplay3}"></TabItem>
    </TabControl>

since your views are defined as static resource use StaticResource instead of binding