How to Change WebView url source at runtime MAUI .NET?

Francisco Jose Goñi 41 Reputation points
2023-01-16T18:07:47.33+00:00
I want to change MAUI .NET Webview Source at runtime.

I have this code, which is summoned by a button in XAML

C# CODE:

`void OnReloadWebView(object sender, EventArgs e)
{  
   try
   {
        WebView = new WebView();
        WebView.Source = new UrlWebViewSource
        {
            Url = "https://blog.xamarin.com/"
        };
        WebView.Reload();
   }
   catch (Exception ex)
   {
     Debug.WriteLine(ex.Message);
   }
}
 `
XAML TAG

` <StackLayout Margin="10">
        <Button Clicked="OnReloadWebView" Text="Recargar"></Button>
        <ProgressBar Progress ="0.1" HorizontalOptions="FillAndExpand" x:Name="progress"/>
        <WebView x:Name="WebView" VerticalOptions="FillAndExpand"  
                     Navigating="WebView_OnNavigating"
                     Navigated="WebView_OnNavigated"/>
    </StackLay>`
Does anyone know if this is possible?

I was expecting for the Webview to reload and change the url but nothing happened not even seems to be reloading...
Developer technologies | .NET | .NET MAUI
Developer technologies | XAML
Developer technologies | XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Anonymous
    2023-01-17T03:26:10.5033333+00:00

    Hello,

    If you want to change the url when click the button at the runtime.

    • Firstly, please use WebView directly, no need to new webview.
    • Second, No need to reload webview, just set the url directly.

    You can refer to the following code.

    void OnReloadWebView(object sender, EventArgs e)
        {
            try
            {
                
                WebView.Source = new UrlWebViewSource
                {
                    Url  "https://blog.xamarin.com/"
                };          
            }
            catch (Exception ex)
            {
                 Debug.WriteLine(ex.Message);
            }
        }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.