Loading XAML from external location

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

When working with XAML in general, like with Workflow or even WPF you might get following error:

Cannot create unknown type '{clr-namespace:YOURNAMESPACE}YOURCONTROL'.' Line number '' and line position ''.

This error will occurred if the XAML file is loaded from external location. In a case of WPF this would look like:

using (var reader = new StreamReader(XamlFile))
{

      UserControl control = (UserControl)XamlReader.Load(reader.BaseStream);
      control.Name =
"m_MyExternalControl";
     
this.AddChild(control);
}


When loading XAML files this way all namespaces in XAML have to be fully qualified. Usually Visual Studio designer holds project references to all controls as long the control (XAML) is bound to project and the
BuildAction (in property windows of XAML file) is set on ‘Page’. That means tha VS has enough information about control and XAML. Because of that VS will shorten the namespace as shown in following XAML snippet:

 

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             Background ="Green"
             xmlns:ctrl="clr-namespace:MyCustomControls"
             d:DesignHeight="300" d:DesignWidth="300">

 

Unfortunately, when you take this control (XAML-file) out of project and load it by XamlReader as shown above the control will fail compilation right after load process ha been completed.

Cannot create unknown type '{clr-namespace:MyCustomControls}MyControl.' Line number '' and line position ''.

To fix this you simply need to add the full qualified assembly name of the control:

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             Background ="Green"
            xmlns:ctrl="clr-namespace:MyCustomControls;assembly=MyCustomControllsAssembly"
             d:DesignHeight="300" d:DesignWidth="300">


Posted Jan 29 2013, 07:30 AM by Damir Dobric
Filed under: ,
developers.de is a .Net Community Blog powered by daenet GmbH.