03 October 2015

Best Practices – XAML & Silverlight

While working on Silverlight projects for past couple of years, I have collated a list of best practices for Silverlight and XAML.

Performance

Best Practice
Reason
1.        
Don’t use unnecessary “xmlns” namespaces in the XAML file.
·         Tip - If you are using Resharper, it will change the color of the unnecessary items to Grey.

This overburdens the load time of the Silverlight page
2.        
Remove all unnecessary resource keys if they are not in use.

They increase memory usage
3.        
Try to use StaticResource instead of DynamicResource
1.       It improves performance.
2.        Helps in detecting exceptions at compile time rather than at run time.

4.        
Minimize your download size – Add only required assembly references and resources (images, CSS, JavaScript etc.) to your Silverlight project.

This reduces time taken to load the application
5.        
Minimize Disk & Network I/O – Try to use chunky calls instead of chatty ones. Retrieve data in a batch rather than contacting server repeatedly.

This reduces performance overhead due to network and disk latency.
6.        
Load Fewer Assemblies at Startup – Load only required assemblies at startup of application. Download additional assemblies either in background later or on demand.

This reduces the startup time for application
7.        
Try to reduce usage of transparent background
Transparent background has a significant effect on performance
8.        
Minimize use of FindName calls: FindName method finds the target by walking through the entire XAML tree.

This affects the performance significantly.
9.        
Hide unused controls in full screen: When the application goes into full screen mode, unused objects need to be hidden.

This makes the page lighter and faster in full screen mode.
10.     
Remove dead XAML.  If a style or a part of your tree is no longer used, remove it.
This will lead to better performance of your page.

11.     
Prefer Templates over UserControls.

This is especially important in say, a DataGrid cell template, where hundreds of cells are styled the same way.  If you style your cell using a UserControl, you are going to parse the same XAML hundreds of times over.  By using a template you ensure that this XAML is only parsed once!

UserControls need to be re-parsed per instantiation, templates are parsed only once. This improves performance.
12.     
Minimize your element count – Add only required XAML elements which contribute to appearance, formatting & functionality.


Every element that you add to the visual tree adds to the amount of time that it takes to parse
13.     
Don’t add same namespaces multiple times in a single XAML page. It leads to duplication and loads the assembly namespace multiple times.
This can lead to memory issues at runtime.

14.     
Give name to only required controls in XAML which will be used specifically in code behind or XAML

Note – This contradicts with naming convention best practice though. 

It reduces unnecessary object creation at page load and improves performance.

Code building


Best Practice
Reason
1.        
When adding a control that has no elements inside it, better to close it by self-closing tag “/>” instead of the hard closing tag (</TAG>).

This gives cleaner XAML code.

2.        
Don’t use extra panels (e.g. Grid, StackPanel, Canvas etc.) unless it is required.

This gives cleaner XAML code.

3.        
Always try to use Grid as your first layout panel. Also try to use Grid as container for other controls.

Grid has the flexible UI layout and resizes itself as per the controls placed in it.

4.        
Use the Visibility property of the controls instead of the Opacity property to hide the content.
Opacity to zero makes the control to hide but takes space in both memory and the UI.

Visibility property collapses the control from the UI, thus making space for other controls.

5.        
Use proper formatting of your XAML code.
This gives better look of code and also easy to maintain in future.

6.        
Use comments in XAML whenever require.
This is useful when you revisit the code after a long time or some other person comes to work with your XAML file.

7.        
Remove unnecessary styles & storyboard animations if they are not required.

Reduces cluttering of XAML code.
8.        
Try to add your styles in a separate file if you want to share them across your application.

If they are specific to a single page then add them in the page resource.

Helps in code separation and easy maintenance.
9.        
As Silverlight is resolution dependant, it is advisable to use auto-resizing components.


10.     
A canvas control does not resize itself. Hence it has to be used only in cases where the height and width are to be fixed.


11.     
Avoid applying themes to DataGrid control: Silverlight provides a DataGrid control which has binding property to display data in the form of Grid. Themes should not be applied to the DataGrid as its performance degrades (specially the datagrid scrollbar) significantly when themes are applied. It is also affected when using opacity property.


12.     
Use RowDefinitions & ColumnDefinitions with star (*) value to structure the layout.
This will ensure that the website will fit in any resolution.



Naming conventions



Best Practice
Reason
1.        
Try to specify an x:Name attribute for every element in XAML
Note - This however has a performance implication. So if application performance is slow in end, you can try removing x:Name attribute for elements where not required.

Forcing an x:Name on an object really makes you think of the purpose of that element and whether it is really required.
2.        
Use proper name for your “xmlns” namespace prefix. For example: xmlns:commonControls is more meaningful than xmlns:cctrl.
This avoids multiple declarations of namespaces in future & creates meaningful prefixes.
3.        
Be consistent. Use the same xmlns namespace abbreviation across all XAML files, and use a consistent abbreviation technique.


4.        
When assigning a name, use the x:Name attribute for consistency.


5.        
Use Pascal casing.

More readable & self-explanatory.
6.        
Provide meaningful names. Instead of a name like border1, use something like TrackBackgroundBorder.

Meaningful.
7.        
Make the x:Name attribute the first attribute after a type instance, like this:
<Button x:Name="CancelButton" ... />

Consistency
8.        
All resources should have an x:Key attribute. Silverlight allows you to use the Name attribute instead of Key, but avoid that practice for consistency with WPF.

Consistency
9.        
For resource keys, use Pascal casing and follow the same meaningful postfix convention followed for x:Names.

More readable & self-explanatory.
10.     
It is good to have each attribute on a separate line.


11.     
If keeping multiple attributes on same line, they should be related and grouped such as HorizontalAlignment and VerticalAlignment


12.     
Instead of pre or post-fixing element names, give them a descriptive name.  Instead of:
a.        btnSubmit use SubmitButton,
b.       grdContent use ContentPanel,
c.        stkPnlNav use NavigationPanel.


No comments: