Positioning in Silverlight 2

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”>
<TranslateTransform X=”0″ Y=”0″ />
<ScaleTransform ScaleX=”1″ ScaleY=”0″ />
<RotateTransform Angle=”0″ />
<SkewTransform AngleX=”0″ AngleY=”0″ />

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


3 comments so far

  1. […] Positioning in Silverlight 2 (Corey Schuman) […]

  2. Ryan on

    I know it is not as nice as a built in property but couldn’t you use some kind of extension method to get the same effect?

  3. Marvin Varela on

    Have you tried assigning an x:Name to the TranslateTransform you want to use?

    I tried this:

    And from C# I was able to do this:

    this.LayoutRootTranslateTransform.X = 0;

    It compiled without any problem!

    Try it and let me know if it works for you.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: