我有一个 XAML 网格的字符串表示形式,如下所示:
<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>
我需要做的是用这个字符串创建一个 Grid 对象。我尝试了很多方法,但到目前为止最接近的是下面的代码:
string content = "<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>";
// 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;
但是,发生 XamlParsedException 表示缺少根元素。
我在 XAML 代码中是否有我看不到的错误?还是方法不好?
感谢您的回答