3

我正在尝试以XamlWriter最简单的方式保存一组对象。出于某种原因,将它们保存为数组会产生无效的 XML:

var array = new int[] {1, 2, 3};
Console.Write(XamlWriter.Save(array));

输出:

<Int32[] xmlns="clr-namespace:System;assembly=mscorlib">
   <Int32>1</Int32>
   <Int32>2</Int32>
   <Int32>3</Int32>
</Int32[]>

尝试使用XamlReaderthrows 阅读此内容:

'[' 字符,十六进制值 0x5B,不能包含在名称中。第 1 行,第 7 位

我尝试另存为,List<T>但我得到了通常的 XAML 泛型错误。有什么简单的方法可以做到(最好使用 LINQ)还是必须定义自己的包装器类型?

4

2 回答 2

3

XamlWriter.Save产生无效的 XML。

<Int32[] xmlns="clr-namespace:System;assembly=mscorlib">
   <Int32>1</Int32>
   <Int32>2</Int32>
   <Int32>3</Int32>
</Int32[]>

我不知道这背后的原因,但使用XamlServices.Save似乎可以解决问题。

<x:Array Type="x:Int32" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <x:Int32>1</x:Int32>
  <x:Int32>2</x:Int32>
  <x:Int32>3</x:Int32>
</x:Array>

Additional notes from MSDN

The following classes exist in both the WPF assemblies and the System.Xaml assembly in the .NET Framework 4:

  • XamlReader
  • XamlWriter
  • XamlParseException

The WPF implementation is found in the System.Windows.Markup namespace, and PresentationFramework assembly.

The System.Xaml implementation is found in the System.Xaml namespace.

If you are using WPF types or are deriving from WPF types, you should typically use the WPF implementations of XamlReader and XamlWriter instead of the System.Xaml implementations.

For more information, see Remarks in System.Windows.Markup.XamlReader and System.Windows.Markup.XamlWriter.

于 2012-10-12T10:29:14.430 回答
1

使用UIElementCollection而不是数组怎么样?UIElementCollection很好地序列化:

var buttonArray = new Button[] { new Button(), new Button() };
var root = new FrameworkElement();
var collection = new UIElementCollection(root, root);

foreach(var button in buttonArray)
    collection.Add(button);

Console.Write(XamlWriter.Save(collection));

给你:

<UIElementCollection Capacity="2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button />
    <Button />
</UIElementCollection>
于 2012-10-12T09:42:57.210 回答