1

I need to refresh webView control when the ui size changed. I used SizeChanged event in some controls like Border, WebView, etc SizeChanged event. But I got this system.invalidoperationexception 'a method was called at an unexpected time error. I got this error at the beginning of running the application. The way I used:

<WebView x:Name="webView" SizeChanged="OnSizeChanged" HorizontalOptions="FillAndExpand"  VerticalOptions="FillAndExpand">
     <WebView.Source>
          ...
     </WebView.Source>
</WebView> 
private void OnSizeChanged(object sender, EventArgs e)
{
      webView.Reload();
}

Probably I used it in wrong way, or could it be a bug?

shalom
  • 191
  • 1
  • 1
  • 10
  • I suspect there is an OnSizeChanged call "too early", before the webView is "ready". Try `if (webView.IsVisible) webView.Reload();`. Might need to do other checks also. Maybe check if webView has zero width or height, don't reload. – ToolmakerSteve Oct 17 '22 at 21:55
  • Well, I tried null check, IsLoaded, IsVisible states but I got the same error. I don't know why but when I used it in try catch, I didn't get the error again and the program started working properly. – shalom Oct 17 '22 at 22:25

1 Answers1

0

I solved the problem when I used Reload method in try-catch:

private void OnSizeChanged(object sender, EventArgs e)
{
    try
    {
        webView.Reload();
    }
    catch(Exception ex)
    {
        
    } 
}
shalom
  • 191
  • 1
  • 1
  • 10
  • The reason this works is straightforward. `OnSizeChanged` gets called once, "too early" as I mentioned in a comment. (Because the size changes from (0,0) to the actual size.) You catch the invalidoperationexception, so the program continues to run. Then later, `OnSizeChanged` gets called as you expected, there is no exception - the Reload occurs. This can easily be seen by adding Debug output to show old size and new size. And to print the exception when it occurs. – ToolmakerSteve Oct 18 '22 at 03:37