Search code examples
c#wpfconvertersmarkup-extensions

Creating Markup Extension with Converter


I'm trying to create a Markup Extension that will take a string of HTML, convert it to a FlowDocument, and return the FlowDocument. I'm fairly new to creating Markup Extensions and I'm hoping this will be obvious to someone with more experience. Here is my code:

[MarkupExtensionReturnType(typeof(FlowDocument))]
public class HtmlToXamlExtension : MarkupExtension
{
    public HtmlToXamlExtension(String source)
    {
        this.Source = source;
    }

    [ConstructorArgument("source")]
    public String Source { get; set; }

    public Type LocalizationResourceType { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (this.Source == null)
        {
            throw new InvalidOperationException("Source must be set.");
        }

        FlowDocument flowDocument = new FlowDocument();
        flowDocument.PagePadding = new Thickness(0, 0, 0, 0);
        string xaml = HtmlToXamlConverter.ConvertHtmlToXaml(Source.ToString(), false);

        using (MemoryStream stream = new MemoryStream((new ASCIIEncoding()).GetBytes(xaml)))
        {
            TextRange text = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
            text.Load(stream, DataFormats.Xaml);
        }

        return flowDocument;
    }
}

Update: Here is the XAML.

<RadioButton.ToolTip>
    <FlowDocumentScrollViewer Document="{ext:HtmlToXaml Source={x:Static res:ExtrudeXaml.RadioButtonCreateBody_TooltipContent}}" ScrollViewer.VerticalScrollBarVisibility="Hidden" />
</RadioButton.ToolTip>

And my VS error list:

  • Error 3 Unknown property 'Source' for type 'MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension' encountered while parsing a Markup Extension. Line 89 Position 49.
  • Error 1 The type "HtmlToXamlExtension" does not include a constructor that has the specified number of arguments.
  • Error 2 No constructor for type 'HtmlToXamlExtension' has 0 parameters.

Solution

  • You implemented you MarkupExtension without default constructor: So you have 2 options:

    1. Delete your specific constructor (Anyway you set Source directly)
    2. Change invocation of you HtmlToXamlExtension if you remove Source= part, then Wpf will try to find constructor matching all unnamed fields right after ext:HtmlToXaml part:

      <RadioButton.ToolTip>
        <FlowDocumentScrollViewer 
               Document="{ext:HtmlToXaml {x:Static res:ExtrudeXaml.RadioButtonCreateBody_TooltipContent}}" 
               ScrollViewer.VerticalScrollBarVisibility="Hidden" />
      </RadioButton.ToolTip>
      

      UPD: Even though it works, but MSDN says, that you should have default constructor

    Hope it helps.