WPF图像源本身将变为空

WPF图像源本身将变为空,wpf,image,canvas,Wpf,Image,Canvas,我有一个画布,我把图像放入其中,比如: Image img = new Image() { Source = new BitmapImage(new Uri(cardImages[0].Last(), UriKind.Relative)) }; CardStackCanvas1.Children.Add(img); CardStackCanvas1.InvalidateVisual(); 在这些行之后,如果我检查画布的子项,那么图像应该在那里,并且具有正确的源代码 如果我在添加图像的

我有一个
画布
,我把
图像
放入其中,比如:

Image img = new Image()
{
    Source = new BitmapImage(new Uri(cardImages[0].Last(), UriKind.Relative))
};

CardStackCanvas1.Children.Add(img);
CardStackCanvas1.InvalidateVisual();
在这些行之后,如果我检查
画布的子项
,那么
图像
应该在那里,并且具有正确的
源代码


如果我在添加
图像的方法完成后,查看
画布
包含的内容(例如通过创建MouseUp事件),则
图像
仍然存在,但它的
源代码现在是
null
。我现在不知道。

我想您更改了
cardImages
数组元素,它们是图像源。您应该为图像源提供另一个变量

解决方案:

string imageSourceString = cardImages[0].Last();
Image img = new Image()
{
    Source = new BitmapImage(new Uri(imageSourceString, UriKind.Relative))
};

你的假设是错误的。以后更改数组时,从第一个
cardImages
元素创建的位图图像不会更改。