Click here to Skip to main content
15,943,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear all,

In my application I would like to read some XAML code and create some UI controls described by it. I used the following code:

UIControlClass uiControl = (UIControlClass)System.Windows.Markup.XamlReader.Load(streamContainingTheXAMLcode);

and it worked fine for controls like Buttons and Grids, for example, but when I tried to create the whole window (which by the way is of class Window1 : Window) XamlParseException which says:

"'Class' attribute does not exist in XML namespace '' namespace. Line '4' Position '5'."

was thrown. If I remove part of XAML code which determines Class of my window, in this particular case

the exception is not thrown and the above C# code works, but the window created is of Class Window and I lose all my Window1 functionality.

Is there any way to explain to XamlReader what "'Class' attribute" is, and if so, how?
Also, if three is some other way to read XAML code and create controls based on it, that would be satisfactory solution, too.

Thanks in advance.
Updated 4-Feb-11 9:12am

1 solution

You cannot use XamlReader.Load to load Xaml that's associated with a code behind file. Remove the code behind file, use XamlReader.Load to get a Window object and then add the required event handlers at runtime (as opposed to overriding virtual methods in your Window derived class).

Alternatively use msbuild to compile the Xaml/cs files at runtime and then load it via reflection.
Share this answer
dsnlkc 5-Feb-11 7:28am    
Thanks. That saved me a lot of time. First method I understand (I thought I would have to do something like that), but now I'm intrigued by that method which involves compiling and loading compiled code at runtime. Could you elaborate it a bit more, or give me link(s) to some documentation? I didn't know that it is even possible so please include the very basics, too.

Thanks again.
Espen Harlinn 6-Feb-11 15:14pm    
Good answer, a 5
Nish Nishant 6-Feb-11 21:26pm    
Thank you, Espen!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900