我正在尝试以编程方式生成一个StackPanel
并向其添加一个Image
。但是,我得到了一个空的StackPanel
。我认为我的代码没有问题,也没有抛出任何异常:
StackPanel Sp = new StackPanel();
Sp.Orientation = Orientation.Horizontal;
Image Img = new Image();
BitmapImage BitImg = new BitmapImage(new Uri(
"/MyProject;component/Images/image1.png", UriKind.Relative));
Img.Source = BitImg;
Sp.Children.Add(Img);
[编辑]
我尝试了另一种添加图像的方式,它起作用了。这让我很好奇,因为它们在我看来本质上是相同的:
下面的代码可以工作(显示图像):
Image Img = new Image();
Img.Source = new BitmapImage(new Uri(
"pack://application:,,,/MyProject;component/Images/image1.png"));
以下代码无法工作(图像缺失):
Image Img = new Image();
BitmapImage ImgSource = new BitmapImage(new Uri(
"pack://application:,,,/MyProject;component/Images/image1.png",
UriKind.Relative));
Img.Source = BitImg;
它们为什么不同?