动态添加 wpf 控件以环绕面板 [英] adding wpf controls dynamically to wrap panel

查看:51
本文介绍了动态添加 wpf 控件以环绕面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将控件动态添加到窗口上的环绕面板,但在将两个环绕面板控件添加到原始环绕面板控件后,它不再添加这里是我用来添加图像的代码

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();

我是 wpf 的新手,只是想知道我是否做错了什么或遗漏了什么.

im new to wpf and just wondering if im doing something wrong or missing something.

任何帮助将不胜感激

编辑

        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;

    }

推荐答案

为了在容器控件中随机放置图像,您不应该使用 WrapPanel,而是使用 Canvas.Canvas 用于元素的绝对定位.您可以通过设置 Canvas.LeftCanvas.Top 属性(或 Canvas.RightCanvas.Bottom).

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

此外,您不需要任何内部"面板,因为 Image 是一个可以直接添加到任何容器的控件.

Moreover you don't need any "inner" panel, as Image is a control that can be added directly to any container.

所以像这样改变你的 displayimage 方法:

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

InvalidateVisual 不是必需的.

您可能还需要注意图像不会被多次添加,因为 Random.Next 可能会多次返回相同的数字.

You might also have to take care that images aren't added multiple times, since Random.Next may return the same number multiple times.

这篇关于动态添加 wpf 控件以环绕面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆