是否可以让XamlWriter保存StaticResource?

时间:2017-08-15 22:11:16

标签: wpf xaml xamlwriter

我的问题显示在以下程序中,其中GeometryModel3D的材质是从XAML中的StaticResource设置的。

是否有可能让XamlWriter保存出实际的StaticResources而不是已解析的引用(它现在会这样做)?如果是这样,我需要做什么?

using System;
using System.IO;
using System.Text;
using System.Windows.Controls;
using System.Windows.Markup;

namespace MaterialTest
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            string xaml = "";
            xaml += "<Viewport3D xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>";
            xaml += "  <Viewport3D.Resources>";
            xaml += "    <DiffuseMaterial x:Key='Steel' />";
            xaml += "  </Viewport3D.Resources>";
            xaml += "  <ModelVisual3D>";
            xaml += "    <ModelVisual3D.Content>";
            xaml += "      <GeometryModel3D Material='{StaticResource Steel}'>";
            xaml += "        <GeometryModel3D.Geometry>";
            xaml += "          <MeshGeometry3D Positions='-0.5,-0.5,0 0.5,-0.5,0 0.5,0.5,0 -0.5,0.5,0' TriangleIndices='0 1 2 0 2 3' />";
            xaml += "        </GeometryModel3D.Geometry>";
            xaml += "      </GeometryModel3D>";
            xaml += "    </ModelVisual3D.Content>";
            xaml += "  </ModelVisual3D>";
            xaml += "</Viewport3D>";

            MemoryStream buffer = new MemoryStream(Encoding.UTF8.GetBytes(xaml));
            Viewport3D viewport = XamlReader.Load(buffer) as Viewport3D;

            string xaml_out = XamlWriter.Save(viewport);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

  

是否有可能让XamlWriter保存出实际的StaticResources而不是已解析的引用(现在它已经完成)?

不,我担心不是。这是MSDN上记录的XamlWriter.Save的已知限制:https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/serialization-limitations-of-xamlwriter-save

  

序列化过程将取消引用各种标记扩展格式(例如StaticResourceBinding)对对象的公共引用。在应用程序运行时创建内存中对象时,这些已被解除引用,并且Save逻辑不会重新访问原始XAML以恢复对序列化输出的此类引用。