UWP XAML content alignment brain teaser


5 years ago

I usually find positioning content in XAML more comfortable than in CSS. However, I got stuck with an alignment problem which turned out to have an elegant solution. Let's look at this brain teaser together! Consider the following layout:

We have a stretched button which has a maximum width of 250 . The result looks like this:

UWP button stretched centered

What if we now wanted to align the stretched button to the left or the right? That turns out to be quite challenging. You cannot specify a horizontal alignment like StartAndExpand and EndAndExpand - these options are available in Xamarin.Forms only. Applying HorizontalAlignment in the containing Grid changes the rules completely - it forces the Button to have the minimum possible width it needs, so stretching no longer has the intended effect. If you want to tackle this brain teaser yourself, take a break from reading here and try it! If you find a different solution than the one presented, please let me know in the comments!

Left alignment

We can move the MaxWidth attribute to a ColumnDefinition in our grid and make the single column * (star) wide:

The column of the Grid is stretched but has a maximum width of 250 . Columns in Grid start on the left-hand side, so the column is left-aligned as well but the button within it can still stretch.

Left-aligned stretched button

Right alignment

One column is not sufficent for right-alignment, but we can use a very similar trick again with two columns:

The button will now resides in the second column, which has the same properties as in the previous example. The new first column has * (star) width as well and its purpose is to fill the space remaining after arranging the second column. This sort of works. Sort of - unless the screen is narrow. In that case, the rule which states that columns of * width evenly distribute the available width of the Grid takes precedence and both columns have get the same width.

Narrow window evenly distributes Column widths

We need to find another way out. We must trick the Grid into thinking the second column should be significantly wider by default:

By giving the second column width of 10000* its width, Grid would by default make the second column 10000 times as wide as the first. Now in combination with MaxWidth it constrains the width to exactly 250 even on narrow screen, and we get precisely the result we wanted:

Right aligned stretched button

In case you found a different solution for this brain teaser I would love to know! Please let me know in the comments ‍?? .