I'm trying to make a Markdown renderer for Neo.Markdig.Xaml. The renderer use an XamlObjectWriter to create the graph. In the code below, I'm trying to create a FlowDocument with a single paragraph in it:
using System.Windows.Documents;
using System.Xaml;
XamlSchemaContext context = System.Windows.Markup.XamlReader.GetWpfSchemaContext()!;
using var writer = new XamlObjectWriter(context);
XamlType flowDocumentXamlType = context.GetXamlType(typeof(FlowDocument))!;
writer.WriteStartObject(flowDocumentXamlType);
XamlMember blocksXamlMember = flowDocumentXamlType.GetMember(nameof(FlowDocument.Blocks))!;
writer.WriteStartMember(blocksXamlMember);
XamlType paragraphXamlType = context.GetXamlType(typeof(Paragraph))!;
writer.WriteStartObject(paragraphXamlType);
XamlMember paragraphInlinesXamlMember = paragraphXamlType.GetMember(nameof(Paragraph.Inlines))!;
writer.WriteStartMember(paragraphInlinesXamlMember);
writer.WriteValue("Hello, world!");
writer.WriteEndMember();
writer.WriteEndObject(); // paragraphXamlType
writer.WriteEndMember(); // blocksXamlMember
writer.WriteEndObject(); // flowDocumentXamlType
But it throws the following exception at the line writer.WriteStartMember(paragraphInlinesXamlMember);:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
at System.Xaml.XamlObjectWriter.Logic_ApplyPropertyValue(ObjectWriterContext ctx, XamlMember prop, Object value, Boolean onParent)
at System.Xaml.XamlObjectWriter.Logic_DoAssignmentToParentProperty(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
at Program.<Main>$(String[] args) in C:\TEMP\ConsoleApp1\Program.cs:line 13
I have no idea what I'm doing wrong here and there's very little documentation on the subject.
OK, found it. When we need to write a collection, we have to had theses two lines:
So my code becomes:
Please don't ask me why. The documentation of
WriteGetObject()is: