我试图以编程方式生成一个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);
Run Code Online (Sandbox Code Playgroud)
[编辑]
我尝试了另一种方法来添加图像,它的工作原理.它引起了我的兴趣,因为在我看来它们本质上是一样的:
以下代码WORKS(显示图片):
Image Img = new Image();
Img.Source = new BitmapImage(new Uri(
"pack://application:,,,/MyProject;component/Images/image1.png"));
Run Code Online (Sandbox Code Playgroud)
下面的代码不NOT WORK(图像丢失):
Image Img = new Image();
BitmapImage ImgSource = new BitmapImage(new Uri(
"pack://application:,,,/MyProject;component/Images/image1.png",
UriKind.Relative));
Img.Source = BitImg;
Run Code Online (Sandbox Code Playgroud)
为什么他们不一样?
ele*_*ner 11
Img.Source = new BitmapImage(new Uri(
"pack://application:,,,/MyProject;component/Images/image1.png"));
Run Code Online (Sandbox Code Playgroud)
默认使用UriKind.Absolute而不是UriKind.Relative
如果您希望用户UriKind.Relative- URI应采用不同的格式.看看MSDN
没有repro.
我将您的代码复制/粘贴到Button处理程序并添加了1行:
root.Children.Add(Sp);
Run Code Online (Sandbox Code Playgroud)
提示:在此代码的末尾设置断点,并使用"WPF树可视化器"查看是否所有内容都在您认为的位置.这是Locals and Autos Windows中的小玻璃.
| 归档时间: |
|
| 查看次数: |
28296 次 |
| 最近记录: |