I'm trying to add controls dynamically to a wrap panel on a window but after two wrap panel controls are added to the original wrap panel control it doesn't add anymore here is the code im using to add the image
Random rn = new Random();
ImageContainer.Children.Add(displayimage(rn.Next(amount)));
ImageContainer.InvalidateVisual();
im new to wpf and just wondering if im doing something wrong or missing something.
any help would be greatly appreciated
EDIT
public WrapPanel displayimage(int i)
{
WrapPanel pn = new WrapPanel();
pn.Width = 350;
pn.Height = 400;
pn.Background = new SolidColorBrush(Colors.White);
BitmapImage bm = new BitmapImage(new Uri(imagePaths[i]));
Image im = new Image();
im.Source = bm;
im.Height = 300;
im.Width = 400;
im.Margin = new Thickness(25,25,25,25);
pn.Children.Add(im);
pn.Margin = Location(pn);
pn.ClipToBounds = true;
return pn;
}
In order to put images at random places in a container control, you should not use a WrapPanel, but a Canvas instead. Canvas is made for absolute positioning of elements. You set the position of a child element of a Canvas by setting the
Canvas.Left
andCanvas.Top
properties (orCanvas.Right
orCanvas.Bottom
).Moreover you don't need any "inner" panel, as
Image
is a control that can be added directly to any container.So change your
displayimage
method like this:Now add these Images to a Canvas:
The
InvalidateVisual
is not necessary.You might also have to take care that images aren't added multiple times, since
Random.Next
may return the same number multiple times.