whistyun / MdXaml

Markdown for WPF - alternate version of Markdown.Xaml
MIT License
245 stars 37 forks source link

Document is null in class constructor #54

Closed rocksdanister closed 1 year ago

rocksdanister commented 1 year ago

Document get returns null in class constructor but its possible to access Document outside it.

Sample code:

<mdxam:MarkdownScrollViewer x:Name="markdown" ../>

public Sample()
{
  markdown.Document.Blocks.Add(new Paragraph("Null exception")));
}

public void SomeFn()
{
  markdown.Document.Blocks.Add(new Paragraph("This works")));
}
whistyun commented 1 year ago

Has a code which access Document property been tried here?

The initial value of Document property is null for now. And this vlaue is not changed until the Source or Markdown property value is changed.

MarkdownScrollViewer inherits from FlowDocumentScrollViewer. So the Document property can be initialized.

markdown.Document = new FlowDocument(new Paragraph(new Run("some text")));

Be careful not to change the Markdown and Source properties. These properties will update Document property.

rocksdanister commented 1 year ago

Yes, It was old code from when using RichTextBox.

Maybe make Document setter private? initially being null before Markdown or Source can lead to mistakes like this.

whistyun commented 1 year ago

The private access level prevents access to Document property.

I plan to change the Document getter so that it does not return null (it is automatically initialized).

public class MarkdownScrollViewer : FlowDocumentScrollViewer, IUriContext
{

    ・・・

    public new FlowDocument? Document
    {
        get
        {
            var bs = (FlowDocumentScrollViewer)this;
            return bs.Document ??= new FlowDocument();
        }
        set => ((FlowDocumentScrollViewer)this).Document = value;
    }
}

This is not an override, but hides accessible base property. So if MarkdownScrollViewer is cast to FlowDocumentScrollViewer, the problem recurs.


var viewer1= new MarkdownScrollViewer();
viewer1.Document.Blocks.Add(...);  // No error occurres.

var viewer2 = (FlowDocumentScrollViewer)new MarkdownScrollViewer();
viewer2.Document.Blocks.Add(...);  // NullReferenceException occures

Would this amendment help you?

rocksdanister commented 1 year ago

I think this is fine.

whistyun commented 1 year ago

v1.17.0 has be released. The Document does not return null (it is automatically initialized).

rocksdanister commented 1 year ago

Great, I'll close this 🥳