I have a task to write down a simple viewer that would show how a .xaml file visually looks like(just like the VS editor, but without editing capabilities). Could you give me any references that would help me?
you can use XamlReader.Load method
If you want only viewer, not a designer you can call XamlReader.Load method, and assign the result to ContentControl.Content
StringReader stringReader = new StringReader(strXaml);
XmlReader xmlReader = XmlReader.Create(stringReader);
myContentControl.Content = (Button)XamlReader.Load(xmlReader);
EDIT This code loads window from xaml and show it
string strXaml = "<Window xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" Title=\"MainWindow\" Height=\"350\" Width=\"525\">" +
"<Grid> <Button Content=\"Button123\" Height=\"23\" HorizontalAlignment=\"Left\" Margin=\"174,41,0,0\" Name=\"button1\" VerticalAlignment=\"Top\" Width=\"75\" />"+
"</Grid></Window>";
StringReader stringReader = new StringReader(strXaml);
XmlReader xmlReader = XmlReader.Create(stringReader);
Window obj = (Window)XamlReader.Load(xmlReader);
obj.Show();
If you are sure that the root element is allways Window, you can skip it. Something like this works for me
StringReader stringReader = new StringReader(strXaml);
var xDoc = XDocument.Load(stringReader).Document.Descendants().First().DescendantNodes().First();
XmlReader xmlReader = xDoc.CreateReader();
uc.Content = XamlReader.Load(xmlReader);
Would be better to check if Window exists or not before skipping it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With