Friday, May 22, 2009

Dynamic Xaml Upload from ClientBin


I noticed that if silverlight loads a control in xaml, which is in ClientBin folder, at run-time, XamlParseException was thrown.

Following is xaml in ClientFolder:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:nav="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Navigation"
xmlns:telerikEditor="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Editor">










Snippet to load the xaml:
private void LoadContent(string str)
{
WebClient xmlClient = new WebClient();
xmlClient.DownloadStringCompleted += XMLFileLoaded;
xmlClient.DownloadStringAsync(new Uri(str, UriKind.RelativeOrAbsolute));
}

void XMLFileLoaded(object sender, DownloadStringCompletedEventArgs e)
{
string xmlString = e.Result;

// Got all your XML data in to a string
var uc = System.Windows.Markup.XamlReader.Load(xmlString);
var toolBar = (uc as UserControl).FindName("toolbarFile") as RadToolBar;
toolBarTray.Items.Clear();
toolBarTray.Items.Add(toolBar);
}

When I run, I got InvalidOperationException was unhandled by user code.
The error description was "Element is already the child of another element."

The reason is that RadToolBar in the xaml is a child of UserControl. So when trying to add to toolBarTray, it throws the exception.

In order to fix this problem, change the xaml file so that it looks like following:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:nav="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Navigation"
xmlns:telerikEditor="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Editor"
x:Name="toolbarFile">








What I did was removed UserControl tag and copy all xmlns to RadToolBar tag.

And Viola!

my silverlight app runs great!

No comments:

Post a Comment