Positioning in Silverlight 2

Posted by Corey on March 19, 2008 at 9:08 pm.

A common mistake in Silverlight is for people to use the Canvas.Left and Canvas.Top property when positioning elements.  In Silverlight 2, there is a push towards a relative positioning model.  This makes the Margin, HorizontalAlignment, and VerticalAlignment very important (for all you CSS people the Margin starts on the Left and goes clockwise).  So, how do you position, move, or animate elements?  Where is the X and Y?  You can find them in the TranslateTransform which is part of the TransformGroup which is part of the RenderTransform.

XAML (see below for this code to copy)
Transform group
This is a pain to access from C#.  You have to access the TranslateTransform through the Children collection using the index.  What happens if you switch the positions of the Transforms in XAML?  Your code will fail.  Here is the code to access X and Y through C# (again, see below for code to copy).
C Sharp translate transform
So my question: Why not add the X, Y, ScaleX, and ScaleY to the UIElement?  This would eliminate the need to go through multiple castings in C#, it would prevent index failures if you change your transforms in XAML, and it would eliminate the misuse of the Canvas.Left and Canvas.Top properties.

Code to copy:

<Grid x:Name=”LayoutRoot” Background=”White”>
<Grid.RenderTransform>
<TransformGroup>
<TranslateTransform X=”0″ Y=”0″ />
<ScaleTransform ScaleX=”1″ ScaleY=”0″ />
<RotateTransform Angle=”0″ />
<SkewTransform AngleX=”0″ AngleY=”0″ />
</TransformGroup>
</Grid.RenderTransform>
</Grid>

            ((LayoutRoot.RenderTransform as TransformGroup).Children[0] as TranslateTransform).X;
((LayoutRoot.RenderTransform as TransformGroup).Children[0] as TranslateTransform).Y;

5 Responses to “Positioning in Silverlight 2”

Leave a Reply