Sunday, August 8, 2010

Common Code Base 3 handling controls

Another issue you are going to face is the namespace and assembly differences of classes in WPF and Silverlight.Especially you will find when dealing with controls.ie the classes will be there with same methods and properties.But in different namespaces or assemblies .That prevent us from having common code base.

Lets just consider the case of TreeView in System.Windows.Controls namespace which is present in both WPF and Silverlight.In WPF it is in the assembly PresentationFramework.dll but in Silverlight its System.Windows.Controls.dll. Ideally the schema mapping should do the correct mapping and we should be able to use the xaml. But unfortunately it is not mapped to the schema.Means if we use common xaml file for tree view it will show a compilation error in Silverlight.

The tag 'TreeView' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'.

Does this indicate we should stop common code? Not at all.We have one solution which uses inheritance as a hack.I didn’t even think, inheritance will have such a usage.Solution is as follows.

  1. Create your own class for TreeView by inheriting the framework TreeView.Have this linked to WPF too.
  2. Use your treeview throughout the application.
Public Class CCBTreeView
Inherits System.Windows.Controls.TreeView
End Class


CCBTreeView would be in your controls project which refers PresentationFramework.dll and System.Windows.Controls.dll in WPF and Silverlight respectively. While using, use as follows.


<UserControl x:Class="TestCompatibility.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:CCBControls="clr-namespace:CCB.Controls;assembly=CCB.Controls">
<CCBControls:CCBTreeView ItemsSource="{Binding Persons}" />
</UserControl>


This applies to so many controls such as HierarchicalDataTemplate,TabControl etc which differs in namespace or assembly.Refer the sample uploaded here if you still have confusion.Also let me know if anybody have better solution to this problem.

Previous posts on Common Code Base

----------------------------------------------

Common Code Base 1 Introduction

Common Code Base 2 Styles and Templates

No comments:

Post a Comment