2011-07-27 55 views
7

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

下面的代码并NOT WORK(图像丢失):

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

他们为什么不同?

+1

确保图像文件的URI是正确的,你还需要设置img.Width和img.Height属性的预期值。 – Dotnet

+1

您是否将堆栈面板添加到某个已经存在于您的xaml中的其他面板..?除非你添加stackpanel到一些面板它不会得到渲染在屏幕上..确保添加stackpanel到现有面板 – Bathineni

+0

设置宽度和高度,但仍然没有图像。该图像位于Images文件夹中。 – KMC

回答

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

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

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

+0

THX :-)这并不好笑,因为在uri中使用错误的字符串时未检测到异常。 – mnemonic

5

没有再现。

我你的代码复制/粘贴到一个按钮处理程序,并添加1线:

root.Children.Add(Sp); 

提示:在此代码的末尾设置一个断点,并使用“WPF树可视化”,看看是否一切你认为它是什么。这是当地人和汽车Windows中的小玻璃杯。

+0

谢谢,但似乎并不是问题所在。我改变了我的代码,它有效,但我仍然不明白。请看我编辑的问题。 – KMC

0

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

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; 
相关问题