您只能通过仅在 XAML 中声明实例并将 DataContext 绑定到该实例来在 XAML 中设置 DataContext。
但是由于您要求更清洁的方式,所以理想的是将 TabControl 的 ItemsSource 绑定到 ViewModel 的集合,以便所有 tabItems 自动具有不同的 DataContext。
首先创建 DummyViewModel 并在您的主窗口 ViewModel 中有 ObservableCollection<DummyViewModel> 集合。
public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
ViewModelCollection = new ObservableCollection<DummyViewModel>();
ViewModelCollection.Add(new DummyViewModel("Tab1", "Content for Tab1"));
ViewModelCollection.Add(new DummyViewModel("Tab2", "Content for Tab2"));
ViewModelCollection.Add(new DummyViewModel("Tab3", "Content for Tab3"));
ViewModelCollection.Add(new DummyViewModel("Tab4", "Content for Tab4"));
}
public ObservableCollection<DummyViewModel> ViewModelCollection { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class DummyViewModel
{
public DummyViewModel(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; set; }
public string Description { get; set; }
}
并像这样在 XAML 中与集合绑定:
<TabControl ItemsSource="{Binding ViewModelCollection}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Description}"/>
</Grid>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
ItemTemplate 是为 标签项的标题 定义的,ContentTemplate 是为 定义的各个 tabItems 的内容。
将创建四个选项卡项,每个选项卡项 DataContext 设置为单独的 DummyViewModel 实例。
快照: