简体   繁体   中英

How can I run Prettify in a WPF WebBrowser to apply syntax highlighting?

I'm creating a WPF application that allows the user to enter text in a TextBox. This text may contain Markdown syntax, which is evaluated by a MarkdownDeep object to convert the text to HTML. I take this output and feed it to a WebBrowser control via a call to NavigateToString . (In other words, the WebBrowser control never actually accesses the internet - it's merely a medium to get the rendered output to display.) Generally speaking, this approach works fantastically and I'm very happy with the results.

Now I'm trying to add a new feature where the user can enter actual code and the HTML output will have syntax highlighting for code blocks (similar to how StackOverflow does it). MarkdownDeep has a really nifty hooks that allows programmers to inject their own syntax highlighting. I wanted to use this example from their website. However, I'm having trouble actually getting the Prettify script to run. I've added the Prettify NuGet package which added a bunch of scripts to my solution. I don't know how to run them in a WPF application though, and all the examples I've found online were for ASP.NET.

I tried to use WebBrowser's InvokeScript method to run the script manually, but I only get COMExceptions (which signify that the script "doesn't exist", even though I can see it in the folder structure).

// In XAML file
<WebBrowser x:Name="HtmlOutput"
            local:WebBrowserBehavior.Html="{Binding RenderedText}"
            LoadCompleted="OnLoadCompleted"/>

// In .cs code-behind
private void OnLoadCompleted(object sender, NavigationEventArgs e)
{
    HtmlOutput.InvokeScript("./Scripts/Prettify/run_prettify.js");
}

I guess my question can be summarized as this: Given a string of HTML, how can I apply the Prettify JavaScript script?

[If it helps, I have included the full source of an example project as a MVCE here ]

Pass the script as absolute path using eg

 System.AppDomain.CurrentDomain.BaseDirectory 

and do not forget to copy your file into output directory. Visual studio can do this automatically for you (mark file as "content" and choose "copy" in properties tab)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM