I am a beginner with WPF, and I am having to do a lot of learning while coding, so please bear with me. I have searched the archives, and couldn't really find any answer that fits my question.
I currently have a view that contains a tab control, which is initially loaded with 2 default tabs, and then additional tabs are added and removed programmatically based on user actions.
The way I do this is by having an observable collection of ViewModels for the different types of Views that I can add and remove.
In my Xaml for the view, I had a few different DataTemplates that are used to determine what kind of view to load.
The issue I'm facing is that when I click from one tab to another, I am seeing a lag - close to one second. I put a break point in the code behind for the view, and noticed that the InitializeComponent()
method is being called for a view every time I click on that tab.
The collection of ViewModels is called ActiveContents
, which holds items of type ActiveContent
. The ActiveContent
class is one I created, and it contains an object named ContentItem
which will hold the ViewModel.
Here are is some of the code from my project:
One of the data templates from the xaml:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
.
.
.
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
<DataTemplate DataType="{x:Type viewmodels:InstallQueueViewModel}">
<local:InstallQueueView DataContext="{Binding Path=DataContext.InstallQueueVM,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</DataTemplate>
.
.
.
<DataTemplate x:Key="DataTemplateTabControlContent">
<ContentControl Content="{Binding ContentItem}"></ContentControl>
</DataTemplate>
</UserControl.Resources>
<Grid>
<TabControl ItemsSource="{Binding ActiveContents}"
SelectedIndex="{Binding SelectedTab, Mode=TwoWay}"
IsSynchronizedWithCurrentItem="True"
ItemContainerStyle="{DynamicResource TabItemContainerStyleSpacedMedium}"
ItemTemplate="{StaticResource DataTemplateTabControlHeader}"
ContentTemplate="{StaticResource DataTemplateTabControlContent}">
</TabControl>
Is there a way to prevent it from loading a new instance of the view every time? Like I said, this is my first time, so it's entirely possible I am just going about this the wrong way - if I should change how I'm doing something, please do let me know.
One thing I guess I should mention is that I'm using MahApps to get a Metro feel for the application. I'm not sure if this is contributing at all to the lag I'm seeing.
I am seeing a lag primarily when I switch to a view that contains a DataGrid
. I am considering changing it to a ListView
since the data is read-only, and I am hoping that will have give me some improvement, but the root cause will still be unresolved.
Any help would be greatly appreciated.