我在MVVM上工作,我有Main View,其中有一个tabcontrol和3个tabitems。现在点击每个tabitems我想显示一个新视图。 (我有三个观点)。
我尝试这样做是:
<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>
View1是:(类似于View2和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是:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
这是ViewModel:
class ViewModel
{
public ViewModel()
{
}
}
为什么TabItem在点击它们时没有显示相应的视图,即使我已经设置了与其视图对应的datacontext。
答案 0 :(得分:1)
您需要绑定DataContext
,然后将每个TabItem绑定到其TabItem
的实例,而不是在每个Content
上绑定ViewModel
。在UserControls他们自己做
<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>
因为您的视图被定义为静态资源使用StaticResource
而不是绑定