1

我的问题显示在以下程序中,其中 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);
        }
    }
}
4

1 回答 1

1

是否可以让 XamlWriter 保存实际的 StaticResources 而不是已解析的引用(它现在这样做)?

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

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

于 2017-08-17T12:59:36.963 回答