我试图编程生成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;
他们为什么不同?
确保图像文件的URI是正确的,你还需要设置img.Width和img.Height属性的预期值。 – Dotnet
您是否将堆栈面板添加到某个已经存在于您的xaml中的其他面板..?除非你添加stackpanel到一些面板它不会得到渲染在屏幕上..确保添加stackpanel到现有面板 – Bathineni
设置宽度和高度,但仍然没有图像。该图像位于Images文件夹中。 – KMC