Programmatically add images and place them on a WPF canvas

I am trying to write a WPF C # application that will be able to generate multiple images (representing planets) and then move them relative to each other. I have a standard winform C # application that does this, but I'm trying to convert it to WPF in order to get around the terrible update issues when moving images quickly.

I have been a software developer for over 20 years, I have been working with .Net / C # for 7 years, but I have never used WPF before this week and scratch my head a bit.

I have a bitmap that I use for all images, and now you need to programmatically add any number of images to the canvas, and then place them in the given positions. The code section that I must now add for each image,

            string BodyName = "Body" + BodyCount.ToString();
            Image BodyImage = new Image
            {
                Width = moonBitmap.Width,
                Height = moonBitmap.Height,
                Name = BodyName,
                Source = new BitmapImage(new Uri(moonBitmap.UriSource.ToString(), UriKind.Relative)),
            };

            MainCanvas.Children.Add(BodyImage);
            MainCanvas.SetTop(BodyImage, NewBody.YPosition);
            MainCanvas.SetLeft(BodyImage, NewBody.XPosition);

(NewBody.YPosition and NewBody.XPosition are both double).

It seems to me that he will add any number of images to the canvas. However, the SetTop and SetLeft methods, which I think are the methods that I need to use to place the images, will not compile, and I get the following message from intellisense

"Member 'System.Windows.Controls.Canvas.SetTop(System.Windows.UIElement,double)' cannot be accessed with an instance reference; qualify it with a type name instead."

As a newbie to WPF, I suppose I'm doing something stupid. Can someone tell me how should I do this?

thank

+3
source share
1 answer

SetTop SetLeft Canvas, Canvas. :

Canvas.SetTop(BodyImage, NewBody.YPosition);
Canvas.SetLeft(BodyImage, NewBody.XPosition);
+6

All Articles