Centered Silverlight 2.0 Content Revisited

by edsilverton

After a while I realised that there was a problem with the “scale-9 grid” approach to centered content I wrote about previously.
I noticed little pixel-wide gaps were visible between bits of UI and lines of text weren’t always aligning with each other.

This was due to the grid positioning the content using un-rounded decimal values. The answer to getting everything centered AND pixel-perfect was going to have to be through code:

public Main()
Application.Current.Host.Content.Resized += new EventHandler(Content_Resized);

void Content_Resized(object sender, System.EventArgs e)
double browserWidth = System.Windows.Application.Current.Host.Content.ActualWidth;
double browserHeight = System.Windows.Application.Current.Host.Content.ActualHeight;

    double top = Math.Floor((browserHeight – UI.ActualHeight) / 2);
double left = Math.Floor((browserWidth – UI.ActualWidth) / 2);

    UI.SetValue(System.Windows.Controls.Canvas.TopProperty, top);
Canvas.LeftProperty, left);

This assumes that your Silverlight control is set to be 100% height and width of the browser window. You also need to have a root Canvas with a nested Grid or Canvas named “UI”.