使图像对象成为多个stackpanel的一部分 [英] Make an image object part of multiple stackpanel

查看:56
本文介绍了使图像对象成为多个stackpanel的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建自定义文件选择器。为此我需要一个Image对象被多个文件夹使用,我将其显示为StackPanel。

I am creating a custom file picker. For that I require one Image object to be used by multiple folder which I have displayed as a StackPanel.

Image image = new Image();
image.Source = new BitmapImage(new Uri("I:/image.jpg"));

foreach(string s in Directory.GetDirectories("I:/"))
{
 StackPanel sp = new StackPanel();
sp.Children.Add(image);
sp.Children.Add(new TextBlock{Text = s,});
}





我的尝试:



这会引发InvalidOperationException,因为我无法将图像的单个实例添加到多个StackPanel。

有什么帮助吗?



What I have tried:

This throws an InvalidOperationException since i cannot add single instance of an Image to multiple StackPanel.
Any help ?

推荐答案

其余的错误信息是重要的一点

The rest of the error message is the important bit
引用:

附加信息:指定的元素已经是合乎逻辑的另一个元素的孩子。首先断开连接。

Additional information: Specified element is already the logical child of another element. Disconnect it first.



您需要在 foreach 循环中创建图像



您还需要将该堆栈面板放入应用程序的可视部分(作为您在XAML中使用的任何容器的子项),否则您将永远不会看到图像


You need to create the image within the foreach loop

You also need to put that stack panel into the visual part of your app (as a child of whichever container you are using in your XAML), otherwise you will never see the images


我不知道你想要实现什么以及为什么,最终布局应该是什么样子,为什么你可能需要这么多堆栈面板。



但至少有一个bug是显而易见的:在循环内创建的堆栈面板的所有实例都会丢失。在每次迭代中,您创建一个新实例,之前创建的实例变为无法访问。循环之后,循环内创建的堆栈面板和文本块的所有实例都变得无法访问。最终,垃圾收集器将丢弃所有这些实例。



要使用这些UI元素,您需要将它们添加为某些父UI元素的子元素。 br />


此外,您似乎正在尝试将相同的图像添加到同一UI的逻辑树中。



-SA
I have no idea what you are trying to achieve and why, what the final layout is supposed to look and why would you possibly need so many stack panels.

But at least one bug is obvious: all the instances of your stack panels created inside the loop are simply get lost. On each iteration, you create a new instance, and previously created instance becomes unreachable. After the loop, all instances of stack panels and text blocks created inside the loop become unreachable. Eventually, all these instances will be discarded by the Garbage Collector.

To use those UI elements, you would need to add them as children of some parent UI element.

Also, it looks like you are trying to add the same image into the logical tree of the same UI.

—SA


这篇关于使图像对象成为多个stackpanel的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆