Placing a UserControl inside a TabItem is pretty basic when using XAML.
<TabControl>
<TabItem>
<local:MyUserControl/>
</TabItem>
</TabControl>
But say I want to load the UserControl using the ViewModel. How would I go about that? For instance
<TabControl ItemsSource="{Binding TabCollection}">
<TabItem Header="{Binding Header}"
Source="{Binding MyUserControl}"> <!-- Source is obviously not a property of TabItem-->
<!-- I'm just using it in this context as an example. Like how a 'Frame' would work -->
</TabItem>
</TabControl>
Assuming My ViewModel has an ObservableCollection that I use to populate the different Tabs, Headers, Background colour and so on, how would I populate a view in the TabItem programmatically?
For instance, Below is a basic sample of the ViewModel:
public class TabViewModel
{
// 'TabModel' is a simple class that acts as a Model for this class (TabViewModel)
// All it does is store strings, integers, etc. as properties
// i.e: the fields 'Header' and 'MyUserControl' in the below method are both strings declared in 'TabModel'
public ObservableCollection<TabModel> TabCollection { get; set; }
public TabViewModel()
{
TabCollection = new ObservableCollection<TabModel>();
PopulateTabCollection();
}
private void PopulateTabCollection()
{
TabCollection.Add(new TabModel()
{
Header = "FirstUserControl",
MyUserControl = "Views/MyFirstUserControl.xaml"
});
TabCollection.Add(new TabModel()
{
Header = "SecondUserControl",
MyUserControl = "Views/MySecondUserControl.xaml"
});
}
}
So what I need to do is display a different view in each Tab through databinding. I'm not even sure if this is even possible. But if it is, kindly educate me.
You can achieve this using DataTemplates. Refer the below code.