I am trying to save a collection of objects with XamlWriter in the simplest way possible. For some reason saving them as an array produces invalid XML:

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

outputs:

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

Attempting to read this using XamlReader throws:

The '[' character, hexadecimal value 0x5B, cannot be included in a name. Line 1, position 7

I've tried saving as a List<T> instead but I get the usual XAML generics error. Is there some simple way I can do it (preferably with LINQ) or do I have to define my own wrapper type?

有帮助吗?

解决方案

XamlWriter.Save produces invalid XML.

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

I don't know the reasons behind that, but using XamlServices.Save seems to fix the problem.

<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.

其他提示

What about using UIElementCollection instead of an array? UIElementCollection serializes nicely:

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));

Gives you:

<UIElementCollection Capacity="2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button />
    <Button />
</UIElementCollection>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top