4

我一直在尝试创建一个使用的小型概念证明,ContentWrapperAttribute但我无法让 XamlXmlReader 或 XamlObjectWriter 尊重它,它只是抛出一个异常,说它不能将“String”添加到集合中。

我已经定义了一个像这样的小对象模型:

[ContentProperty("MyItems")]
public class RootClass
{
    public RootClass()
    {
        this.MyItems = new MyItemCollection();
    }

    public MyItemCollection MyItems { get; set; }
}

[ContentWrapper(typeof(MyItemText))]
public class MyItemCollection : List<MyItem>
{
}

[ContentProperty("Text")]
public class MyItemText : MyItem
{
    public string Text { get; set; }
}

public class MyItem
{
}

我正在尝试使用此代码加载 Xaml:

string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<RootClass xmlns=""clr-namespace:XamlTest;assembly=XamlTest"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
    <MyItem />
    <x:String>test</x:String>
</RootClass>
";
StringReader reader = new StringReader(xml);

XamlReader xamlReader = new XamlXmlReader(reader, new XamlSchemaContext());

XamlObjectWriter xow = new XamlObjectWriter(xamlReader.SchemaContext);
while (xamlReader.Read())
    xow.WriteNode(xamlReader);
xow.Close();

RootClass result = (RootClass)xow.Result;

我收到一条System.Xaml.XamlObjectWriterException说明:“向 'XamlTest.MyItemCollection' 类型的集合添加值引发了异常。” 和一个内部System.ArgumentException异常声称:“值“test”不是“XamlTest.MyItem”类型,不能在这个通用集合中使用。”。

应该由XamlXmlReaderContentWrapperAttribute或 XamlObjectWriter 拾取,还是我误解了此属性的作用?如果没有,有没有人真的让这个工作?

4

0 回答 0