繁体   English   中英

以编程方式将图像添加到StackPanel

[英]Add Image to StackPanel in programmatically

我试图以编程方式生成StackPanel并将Image添加到StackPanel 不知怎的,我得到一个空的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);

[编辑]

我尝试了另一种方法来添加图像,它的工作原理。 它引起了我的兴趣,因为在我看来它们本质上是一样的:

以下代码WORKS (显示图片):

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;

为什么他们不一样?

Img.Source = new BitmapImage(new Uri(
             "pack://application:,,,/MyProject;component/Images/image1.png"));

默认情况下使用UriKind.Absolute而不是UriKind.Relative

如果您希望用户UriKind.Relative - URI应采用不同的格式。 看看MSDN

没有repro。

我将您的代码复制/粘贴到Button处理程序并添加了1行:

  root.Children.Add(Sp);

提示:在此代码的末尾设置断点,并使用“WPF树可视化器”查看是否所有内容都在您认为的位置。 这是Locals and Autos Windows中的小玻璃。

这段代码工作正常

Uri uri = new Uri("/Assets/default.png", UriKind.Relative);    
BitmapImage imgSource = new BitmapImage(uri);    
profileImage.Source = imgSource;

要么

BitmapImage image = new BitmapImage(new Uri("/Assets/default.png", UriKind.Relative));
profileImage.Source = image;

您的第一个代码没有问题。 在该代码的末尾,您应该将StackPanel添加到窗口或窗口内的网格中。 另请注意,图像的构建操作必须是“资源”,并且在图像URI(“/ MyProject ;component/Images/image1.png”)中,“MyProject”应该是程序集的名称,而不是项目的名称。 在项目属性的“应用程序”选项卡中检查程序集名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM