adding wpf controls dynamically to wrap panel

2019-05-14 04:37发布

问题:

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;

    }

回答1:

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 and Canvas.Top properties (or Canvas.Right or Canvas.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:

public UIElement GetDisplayImage(int i)
{
    var bm = new BitmapImage(new Uri(imagePaths[i]));
    var im = new Image
    {
        Source = bm,
        Height = 300,
        Width = 400
    };
    var location = Location(im);
    Canvas.SetLeft(im, location.X);
    Canvas.SetTop(im, location.Y);
    return im;
}

Now add these Images to a Canvas:

Random rn = new Random();
ImageCanvas.Children.Add(GetDisplayImage(rn.Next(amount));

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.