Thursday 6 June 2013

Optimizing View loading performance by limitting visible elements

         Wpf can be quite a system hog, if we forget about certain optimizations. Some of them are a must, and not everyone are aware of them. One of the worst things your user can experience with the UI is clicking a button and waiting 10 seconds for the form to show up. This is why every time you have finished building your Wpf forms and views you should ask yourself a question - is there anything in the view, any particular piece of xaml, that is not visible after the view loads for the first time.

         Are there any controls, which in order for the user to see them, he or she has to click the Expander's Button or maybe switch a TabItem in the TabControl. If the answer is yes, then there's some reworking to do, and some importans milliseconds to sheer off.
         To postpone the moment of loading of most xaml elements it is sufficient to initially set Visibility to collapsed. Whatever is inside will be loaded the moment you set the visibility to visible. In case of expander and the tabcontrol it is different. Both of these controls load their "innards" despite the visibility of the content set to Collapsed. The way to overcome this is by using DataTemplates, and it's best to show it by example.

  1 <TabControl.Resources> 
  2    <DataTemplate x:Key="firstTabItem"> 
  3       <SubViews:Tab1 DataContext="{Binding DataContext.SomeViewModelProperty,
  4           RelativeSource={RelativeSource FindAncestor, 
  5           AncestorType={x:Type TabControl}}}"/> 
  6    </DataTemplate> 
  7    <DataTemplate x:Key="secondTabItem"> 
  8       <SubViews:Tab2 DataContext="{Binding DataContext.SomeViewModelProperty,
  9           RelativeSource={RelativeSource FindAncestor, 
 10           AncestorType={x:Type TabControl}}}" /> 
 11    </DataTemplate>    
 12 </TabControl.Resources>  
 13 <TabItem Header="firstTab" ContentTemplate="{StaticResource firstTabItem}"/> 
 14 <TabItem Header="secondTab" ContentTemplate="{StaticResource secondTabItem}"/



These are rather easy things to do, and the gain is quite visible if you have some more complex xaml inside your tab items.

No comments:

Post a Comment