Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically add images and position them on WPF canvas

Tags:

c#

image

canvas

wpf

I am trying to write a C# WPF app which will be able to generate a number of images (representing planets) and then move them about relative to each other. I've got a standard C# winform app which does this but I'm trying to convert this to WPF to get around the horrible refresh problems when moving images around quickly.

I've been a software developer for more than 20 years, been working with .Net/C# for 7 years but have never used WPF until this week and am scratching my head a bit.

I have a bitmap image which I am using for all the images and now need to programmatically add any of a number of images to a canvas and then put them in set positions. The section of code I currently have to add each of the images is

            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).

This looks to me as though it will add any number of images to the canvas. However the SetTop and SetLeft methods, which I think are the methods I need to use to position the images won't compile and I get the following message from the 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 presume I'm doing something stupid. Can anyone tell me how I should be doing this?

Thanks

like image 880
Tim_McN Avatar asked Feb 15 '14 16:02

Tim_McN


1 Answers

SetTop and SetLeft are static methods of Canvas class and you're referring to them through Canvas instance. Try referring to these methods by the class name:

Canvas.SetTop(BodyImage, NewBody.YPosition);
Canvas.SetLeft(BodyImage, NewBody.XPosition);
like image 123
dkozl Avatar answered Oct 23 '22 19:10

dkozl