I'm very new to MVVM and WPF. I'm trying to build a tabcontrol with tabpages presented as usercontrols and i can't find the reason why the usercontrols don't get loaded when i switch between the tabs.
public partial class WndMain : Window
{
public WndMain()
{
InitializeComponent();
var ViewModelWndMain = new ViewModelWndMain();
this.DataContext = ViewModelWndMain;
}
}
Each tabItem has it's own ViewModel:
<Window x:Class="EasyBulking.WndMain"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModels="clr-namespace:EasyBulking.ViewModels"
xmlns:Tabs="clr-namespace:EasyBulking.GUI"
Title="WndMain" Height="350" Width="525">
<Grid>
<TabControl x:Name="TabsWndMain"
ItemsSource="{Binding Tabs}"
SelectedItem="{Binding SelectedTab, Mode=TwoWay}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type ViewModels:ViewModelTabProfile}">
<Tabs:TabProfile />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:ViewModelTabNutrition}">
<Tabs:TabNutrition />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:ViewModelTabTraining}">
<Tabs:TabTraining />
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding tabName}" />
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
</Grid>
The corresponding ViewModel:
class ViewModelWndMain : ViewModelBase
{
private ObservableCollection<ViewModelTab> tabs = new ObservableCollection<ViewModelTab>();
private ViewModelTab selectedTab;
private ResourceManager resourceManager { get; set; }
public ViewModelWndMain ()
{
resourceManager = new ResourceManager("EasyBulking.Properties.Resources", Assembly.GetExecutingAssembly());
Tabs.Add(new ViewModelTabProfile(resourceManager.GetString("tabProfile")));
Tabs.Add(new ViewModelTabProfile(resourceManager.GetString("tabNutrition")));
Tabs.Add(new ViewModelTabProfile(resourceManager.GetString("tabTraining")));
SelectedTab = Tabs[0];
}
public ObservableCollection<ViewModelTab> Tabs
{
get
{
return tabs;
}
}
public ViewModelTab SelectedTab
{
get { return selectedTab; }
set {
selectedTab = value;
this.RaisePropertyChangedEvent("SelectedTab");
}
}
}
The ProperyChanged event fires but the UI just doesn't update when i switch the tabs.
abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}