Unlike normal C#, in Silverlight, you cannot access a control's coordinate through the object.Location.X and object.Location.Y. Instead, it is more troublesome to get and set the values. An in this article, I'm gonna tell you how to get and set the control's coordinate/location/position.

For example, if you want to add Label on the GUI through the code instead of XAML, you need to do have the following codes:

          Label[] arrayScores = new Label[MAX_PLAYERS]; //MAX_PLAYERS = 4
          for (int i = 0; i < arrayScores.Length; i++)
                {
                    arrayScores[i] = new Label();
                    arrayScores[i].Name = "Scores" + i;
                    arrayScores[i].Width = 50;
                    arrayScores[i].Height = 30;
                }

But that's not nough, you haven't set the coordinates of the Labels. You might think that adding the remaining codes at anywhere can do the job. However, it does not. Remember to put the coordinates setting code AFTER the page is loaded.

1. Add this.Loaded event in the constructor after the InitializeComponent()

    public MainPage()
            {
                InitializeComponent();
                ...
                ...
                this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            }

2. Set coordinates using CANVAS: set position, then add into canvas.


            void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                Canvas.SetLeft(arrayScores[0], SCORE_OFFSET_LEFT);
                Canvas.SetLeft(arrayScores[1], SCORE_OFFSET_LEFT);
                Canvas.SetLeft(arrayScores[2], SCORE_OFFSET_LEFT);
                Canvas.SetLeft(arrayScores[3], SCORE_OFFSET_LEFT);
                canvas1.Children.Add(arrayScores[0]);
                canvas2.Children.Add(arrayScores[1]);
                canvas3.Children.Add(arrayScores[2]);
                canvas4.Children.Add(arrayScores[3]);
            }

Happy coding!

HostForLIFE.eu Silverlight 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.