I am attempting to render some Image objects in a canvas (Layout) on the main form of my application which is called Main. I am using C# and WPF to create the application but am unable to get the images to render from within another class but works without problems in the Main form partial class.
public static void renderStarscape(int density = 200)
{
Main main = new Main();
Random random = new Random();
for (int x = 0; x < density; x++)
{
int starSize = random.Next(1, 10);
int starOpacity = random.Next(10, 30);
int starX = random.Next(0, 800);
int starY = random.Next(0, 500);
Image Star = new Image();
Star.Name = (x < 10) ? "star_0" + x : "star_" + x;
Star.Source = streamImage("star_background.png");
Star.Height = starSize;
Star.Width = starSize;
Star.Opacity = (double)starOpacity / 100;
main.Layout.Children.Add(Star);
Canvas.SetLeft(Star, starX);
Canvas.SetTop(Star, starY);
Canvas.SetZIndex(Star, 0);
}
}
Any help would be great, thanks
You are creating an all
new instance of Mainin the method which is not same as the one shown on UI.Instead pass on the instance of the Canvas to the method and draw on that something like this –
The reason its working in partial declaration of class is that you are using the same instance and not creating the new one for
Main().