Search code examples
wpfxamlxamlwriter

Is it possible to get XamlWriter to save a StaticResource?


My problem is shown in the following program, where the GeometryModel3D's Material is set from a StaticResource in XAML.

Is it possible to get the XamlWriter to save out the actual StaticResources instead of the resolved references (which it does now)? If so, what do I need to do?

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

Solution

  • Is it possible to get the XamlWriter to save out the actual StaticResources instead of the resolved references (which it does now)?

    No, I am afraid it's not. This is a known limitation of XamlWriter.Save that is documented on MSDN: https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/serialization-limitations-of-xamlwriter-save

    Common references to objects made by various markup extension formats, such as StaticResource or Binding, will be dereferenced by the serialization process. These were already dereferenced at the time that in-memory objects were created by the application runtime, and the Save logic does not revisit the original XAML to restore such references to the serialized output.