I'm trying to make a TabControl, populated with few UserControls each with a separate ViewModel.
I've declared it in my XAML like this:
<TabControl Margin="10,10,10,40" ItemsSource="{Binding Test}"> <TabControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" FontSize="16" Padding="5"/> </DataTemplate> </TabControl.ItemTemplate> </TabControl> As you can see I'm trying to obtain the name of the tab through a property located in it's View Model:
public class GeneralTabViewModel : INotifyPropertyChanged { private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; public GeneralTabViewModel() { Name = "Name"; } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } The View Model associated with the window that holds the TabControl is declared as follows:
public class SettingsViewModel { public ObservableCollection<UserControl> Test { get; set; } public SettingsViewModel() { Test = new ObservableCollection<UserControl> { new GeneralTab(), new GeneralTab() }; } } Building the program like this yields an empty Header for the 2 tabs.
How can I bind the TextBlock's Text property to the Name property located in the View Model of the UserControl?
If I change the ItemSource type from ObservableCollection<UserControl> to ObservableCollection<GeneralTabViewModel> I will be able to access the property, but how am I going to visualize the UserControl than?