我工作的一个Windows Phone 7应用程序,我有一个方法
public void PaintButtons()
{
IList p1numlist = GenerateRandom();
IList p2numlist = GenerateRandom();
p1b1.Content = images.ElementAt((int)p1numlist[0]);
p1b2.Content = images.ElementAt((int)p1numlist[1]);
p1b3.Content = images.ElementAt((int)p1numlist[2]);
p2b1.Content = images.ElementAt((int)p2numlist[0]); //This is the line where the exception is generated. Exception: System.InvalidOperationException, Message: Element is already the child of another element
p2b2.Content = images.ElementAt((int)p2numlist[1]);
p2b3.Content = images.ElementAt((int)p2numlist[2]);
//p1b1,p1b2,p1b3,p2b1,p2b2,p2b3 are buttons
//GenerateRandom() method returns a List of unique random numbers of size 3
}
// I am adding images to the <code>images</code> collection using the following code
IList<Image> images = new List<Image>();
public Page1()
{
InitializeComponent();
LoadImages();
}
public void LoadImages()
{
Uri[] uri = new Uri[3];
uri[0] = new Uri("/BtnPics/Blue.png", UriKind.Relative);
uri[1] = new Uri("/BtnPics/Red.png", UriKind.Relative);
uri[2] = new Uri("/BtnPics/Yellow.png", UriKind.Relative);
foreach (Uri u in uri)
{
BitmapImage bmp = new BitmapImage(u);
images.Add(new Image() { Source = bmp });
}
}
我在这一点上卡住了,请帮助。 XAML内容如下:
{C}
有人可以帮助吗?
| VigneshPT |什穆埃尔臧:
因为我意识到,图像的FrameworkElements的集合(图片)。
FrameworkElement可以在逻辑树只有一个父。 (类有一个Parent属性包含的元素的唯一父)。
当你设置的图像按钮的内容属性,图像的Parent属性设置的按钮,当您尝试设置相同的图像到另一个按钮,你会得到异常,因为已经有图片父。
你必须为每个按钮创建一个不同的图像