I have a string representation of a XAML Grid like this:
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Background="Yellow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Label Content="textik" />
</Canvas>
</Grid>
What I need to do is create a Grid object out of this string. I tried a lot of approaches, but so far the closest is the code below:
string content = "<Grid xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Canvas Back开发者_如何转开发ground=\"Yellow\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Label Content=\"textik\" /></Canvas></Grid>";
// the string is created programatically, I just put it here to see what it looks like at the end of the process
Stream stream = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(content));
object objGrid = XamlReader.Load(stream);
Grid myGrid = (Grid) objGrid;
However, the XamlParsedException occurs saying that the root element is missing.
Do I have a mistake in a XAML code that I just cannot see? Or is the approach bad?
Thanks for an answer
What version of the framework are you using? In 4 you have additional classes in System.Xaml that are more flexible. You can use System.Xaml.XamlServices.Load(stream);
to get the exact Grid object in the loose xaml. However, using both 4 and 3.5 in VS2010, your exact code (in the second snippet) returns the expected result. Not sure what the problem is on your side but it might not be the code you posted.
Try also adding xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
to the root Grid element. Also you do not need the xmlns again in Canvas (but it doesn't hurt either - except that your strings become unnecessarily big).
精彩评论