Set control width as per screen resolution and size (Dynamic Layout) XAML

I seen many posts on internet asking about how to set an element width dynamically as per screen resolution.  Did not find a very satisfactory answer. Specially, with Win8 devices where a page size changes with a flip of  landscape and portrait orientation change.

I will skip the XAML options, as i found them to be very noisy. Feel free to add a solution if you have one. Here is the code option.

Set your LayoutAwarePage  width  to “Auto”. Wire a LayoutUpdated event to a method called FixLayout()

In FixLayout method use the “ActualWidth” to get the page current width. Don’t use width, it will have “NaN” value. This is the reason many people get confused with this problem.

double originalWidth = 0;
private void FixLayout()
    if (originalWidth != grid.ActualWidth)
        MyTextBox.MinWidth = grid.ActualWidth * .9;
        MyTextBox.Width = grid.ActualWidth;
        originalWidth = grid.ActualWidth;

Call FixLayout from the constructor of the page, after  this.InitializeComponent(), and in response of LayoutUpdated event. Use a originalWidth variable to protect this method get executed again and again for every action on the page.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s