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[]>

XamlReaderスローを使用してこれを読み取ろうとしています:

「[」文字 (16 進値 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>

MSDNからの追加メモ

次のクラスは、WPF アセンブリと System.Xaml.NET Framework 4のアセンブリの両方に存在します。

  • XamlReader
  • XamlWriter
  • XamlParseException

WPF の実装は、System.Windows.Markup名前空間とPresentationFrameworkアセンブリにあります。

System.Xaml実装は名前System.Xaml 空間にあります。

WPF 型を使用している場合、または WPF 型から派生している場合は、通常、実装の 代わりにXamlReader および の WPF 実装を使用する必要があります。XamlWriterSystem.Xaml

詳細については、 System.Windows.Markup.XamlReader および の備考を参照してください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 に答える