We are writing a Universal Windows Platform application with a UI that is XAML with C#, but I wan't to have a WebView control that just loads up a web page. The WebView control appears to not allow height and width to be "Auto" or "100%", and if we delete the height and width it defaults to 0 values. How do we fix this?
Drop a WebView on your designer and XAML is generated that looks like this:
<WebView x:Name="WebView1" HorizontalAlignment="Left" Height="475" Margin="10,64,0,0" Grid.Row="1" VerticalAlignment="Top" Width="245" LoadCompleted="WebView_LoadCompleted"/>
Note that it defaults with a fixed height and width value, which is almost never going to be what we want for responsive Universal Windows Platform applications.
I've also given our WebView an x:Name="WebView1" value, so we can reference our instance in the code behind.
In our code behind, we'll also load up a web page in to our WebView control. We'll keep this simple and just load our WebView after calling InitializeComponent. Notice that we use the WebView1 instance name that the XAML instantiates and initializes for us.
// Attempt to navigate to the specified URL. Notice that a malformed URL will raise a FormatException
// which we catch and let the user know that the URL is bad and to enter a new well-formed one.
Uri targetUri = new Uri("http://StyleMyImage.com");
catch (FormatException exception)
// Handle errors here
Perhaps you've already tried to edit the height and width to your WebView hoping for an "auto" or "100%" behavior. If not, I encourage you to try to edit the WebView and try that. The trick we'll use to solve this is that our WebView lives inside a Grid control. We will put a SizeChanged event handler on our Grid control by typing in a SizeChanged="Grid_SizeChanged" like this:
<WebView x:Name="WebView1" HorizontalAlignment="Left" Margin="10,64,0,0" Grid.Row="1" VerticalAlignment="Top" LoadCompleted="WebView_LoadCompleted"/>
Then, in our code behind we'll add a function to implement the Grid_SizeChanged event like this:
private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
double remainingWidth = Windows.UI.Xaml.Window.Current.Bounds.Width;
WebView1.Width = remainingWidth;
WebView1.Height = e.NewSize.Height;
Now, you're WebView control should fill the full height and width of your grid control dynamically. When your Grid control changes height and width, then you're WebView control will also change.
Here's the result of my Universal Windows Platform application with a simple WebView control to load StyleMyImage.com