动态添加 wpf 控件以环绕面板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14428456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding wpf controls dynamically to wrap panel
提问by Roy James Schumacher
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.
我是 wpf 的新手,只是想知道我是否做错了什么或遗漏了什么。
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;
}
回答by Clemens
In order to put images at random places in a container control, you should not use a WrapPanel, but a Canvasinstead. Canvas is made for absolute positioning of elements. You set the position of a child element of a Canvas by setting the Canvas.Leftand Canvas.Topproperties (or Canvas.Rightor Canvas.Bottom).
为了将图像随机放置在容器控件中,您不应使用 WrapPanel,而应使用Canvas。Canvas 用于元素的绝对定位。您可以通过设置Canvas.Left和Canvas.Top属性(或Canvas.Right或Canvas.Bottom)来设置 Canvas 的子元素的位置。
Moreover you don't need any "inner" panel, as Imageis a control that can be added directly to any container.
此外,您不需要任何“内部”面板,因为它Image是一个可以直接添加到任何容器的控件。
So change your displayimagemethod like this:
所以displayimage像这样改变你的方法:
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 InvalidateVisualis not necessary.
该InvalidateVisual是没有必要的。
You might also have to take care that images aren't added multiple times, since Random.Nextmay return the same number multiple times.
您可能还需要注意图像不会被多次添加,因为Random.Next可能会多次返回相同的数字。

