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

本文关键字:StackPanel 添加 图像 编程 方式 | 更新日期: 2023-09-27 18:03:44

我正在尝试以编程方式生成一个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);

[EDIT]

我尝试了另一种添加图像的方法,它很有效。它吸引了我,因为在我看来,它们本质上是一样的:

以下代码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;

为什么它们不同??

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

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

默认使用UriKind.Absolute而不是UriKind.Relative

如果你想使用UriKind.Relative,URI应该是不同的格式。查看MSDN

无需重新编程。

我将你的代码复制/粘贴到按钮处理程序中,并添加了1行:

  root.Children.Add(Sp);

提示:在这段代码的末尾设置一个断点,并使用"WPF Tree Visualizer"来查看一切是否都在你认为的位置。这是Locals和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添加到您的窗口或窗口内的网格中。还要注意,图像的生成操作必须是"Resource",并且在图像URI("/MyProject;component/Images/image1.png"(中,"MyProject"应该是程序集的名称,而不是项目的名称。在项目属性的"应用程序"选项卡中检查程序集名称。