11

I'm using the code from the following link: Displaying html from string in WPF WebBrowser control

It works well except when I delete the item containing the html, e.NewValue becomes null and I get an exception. Is there a way to return the WebBrowser control to a blank screen?

Community
  • 1
  • 1
mikelt21
  • 2,728
  • 4
  • 23
  • 33
  • 1
    I found this troubling as well, considering that [Microsoft's documentation](https://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.navigatetostring(v=vs.110).aspx) itself states that "If the *text* parameter is **null**, [WebBrowser](https://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser(v=vs.110).aspx) navigates to a blank document ("about:blank")." Clearly not the case... Also quoted, "**.NET Framework** Available since 3.0," I'm on 4.0. – OhBeWise Oct 06 '15 at 17:09

2 Answers2

21

I found this. Anyone have anything better?

if (wb != null)
{
    if (e.NewValue != null)
        wb.NavigateToString(e.NewValue as string);
    else
        wb.Navigate("about:blank");
}

EDIT:

As poby mentioned in the comments, for .NET 4+ use:

if (wb != null)
{
    if (e.NewValue != null)
        wb.NavigateToString(e.NewValue as string);
    else
        wb.Navigate((Uri)null);
}
mikelt21
  • 2,728
  • 4
  • 23
  • 33
  • In .Net 3.5: wb.Navigate(null) instead of wb.Navigate("about:blank") – Remco te Wierik Dec 08 '14 at 11:05
  • oh cool i'll have to try that out sometime. thanks for the update! – mikelt21 Dec 08 '14 at 14:24
  • 1
    I'm using .Net 4.0 and `wb.Navigate(null)` is ambiguous for two of the method overloads. Attempting `wb.Navigate(string.Empty)` also fails as `string.Empty` is an invalid Uri. The provided solution sufficed, though instead I checked for `!string.IsNullOrEmpty(e.NewValue.ToString())` – OhBeWise Oct 06 '15 at 17:36
  • 10
    For .Net 4 and above, use `wb.Navigate((Uri)null)` avoids the ambiguity and works a charm:) – poby Feb 08 '17 at 01:45
0

I just set the WebBrowserLabel's DocumentText to string.Empty.

ulatekh
  • 1,311
  • 1
  • 14
  • 19