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

时间:2011-07-27 07:57:59

标签: c# wpf

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

[编辑]

我尝试了另一种方法来添加图像并且它有效。它引起了我的兴趣,因为在我看来它们基本上是一样的:

以下代码工作(显示图片):

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

以下代码执行 NOT WORK (缺少图片):

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

为什么他们不一样?

4 个答案:

答案 0 :(得分:10)

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

默认使用UriKind.Absolute而非UriKind.Relative

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

答案 1 :(得分:5)

没有重复。

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

  root.Children.Add(Sp);

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

此代码工作正常

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;