我有一个类似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>

我需要做的是从此字符串中创建一个网格对象。我尝试了很多方法,但是到目前为止,最接近的是以下代码:

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代码中是否有错误?还是方法不好?

感谢您的回答

有帮助吗?

解决方案

您正在使用什么版本的框架?在4中,您在System.XAML中还有其他更灵活的类。您可以使用 System.Xaml.XamlServices.Load(stream); 要在松散的XAML中获取确切的网格对象。但是,使用VS2010中的4和3.5,您的确切代码(在第二个片段中)返回预期的结果。不确定问题在您身边是什么,但可能不是您发布的代码。

其他提示

也尝试添加 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 到根网格元素。另外,您不需要在画布中再次使用XMLN(但这也不会受到伤害 - 除了您的字符串变得不必要的大)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top