So you wanted the root canvas to scale proportionately to the host element to achieve fluid layout, and you tried setting Width=”100%” or Height=”50%”, but then horror struck because of this parser error: “Invalid attribute value 100% for property Width/Height”. Ok, to tell you the truth you cannot set “%” to the Width and Height properties because the % is not accepted. Read on for the solution.
The BrowserHost instance has the Resize() event which fires every time the host element is resized and the ActualWidth/ActualHeight properties which tells the dimension of the host element. So, to automatically resize the root canvas, handles the BrowserHost.Resize() event, and from there you can resize the canvas. Let’s sum it up with VB.NET and C# code:
VB.NET – Page.xaml.vb
Imports System.Windows.Interop
Partial Public Class Page
Inherits Canvas
' Height and width of the canvas in percentage
Private _widthCanvas As Double = 100.0#
Private _heightCanvas As Double = 100.0#
Public Sub Page_Loaded(ByVal o As Object, ByVal e As EventArgs)
InitializeComponent()
AddHandler BrowserHost.Resize, AddressOf BrowserHost_Resize
End Sub
Public Sub BrowserHost_Resize(ByVal sender As Object, ByVal e As System.EventArgs)
Me.Width = CDbl(BrowserHost.ActualWidth) * _widthCanvas / 100.0#
Me.Height = CDbl(BrowserHost.ActualHeight) * _heightCanvas / 100.0#
End Sub
End Class
C# - Page.xaml.cs
public partial class Page : Canvas
{
// Height and width of the canvas in percentage
private double _widthCanvas = 100.0;
private double _heightCanvas = 100.0;
public void Page_Loaded(object o, EventArgs e)
{
InitializeComponent();
BrowserHost.Resize += BrowserHost_Resize;
}
public void BrowserHost_Resize(object sender, System.EventArgs e)
{
this.Width = (double)BrowserHost.ActualWidth * _widthCanvas / 100.0;
this.Height = (double)BrowserHost.ActualHeight * _heightCanvas / 100.0;
}
}
The root canvas now automatically resizes according to _widthCanvas and _heightCanvas value. Anyway, I believe some of you folks might be now saying “I want to scale the root canvas proportionally to width and height of web-page body.” If you said so, you’ve need to instead change the size of the host element. You can use CSS for that purpose. See my example below. Highlighted is where you can change the size of the host element.
Online Demo - Source Code (31.20 kb)