如何动态地将 winform 子窗体嵌入到主 winform 的选项卡控件中?

发布于 2024-11-08 23:19:49 字数 113 浏览 0 评论 0原文

有没有一种方法可以将 Winforms 表单对象传递给包含选项卡控件的主表单,并让主表单将此表单对象加载到其中一个选项卡中?

另一个问题是:表单对象将从与主表单不同的线程实例化。

Is there a way that I can hand a Winforms form object to a main form containing a tab control, and have the main form load this form object into one of the tabs?

An additional wrinkle: the form object will be instantiated from a different thread than the main form.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情绪少女 2024-11-15 23:19:49

我认为当在不同线程上创建表单时它不会起作用,但通常可以通过将表单的 TopLevel 属性设置为 False,然后将其添加到选项卡页控件(或任何其他父控件)来实现此目的。

编辑:您还需要将 Visible 属性设置为 True,因为默认情况下表单是隐藏的。

另外,我刚刚尝试过这个,它确实适用于从另一个线程创建的按钮之类的东西。但是当我用 Form 执行此操作时,我收到了 InvalidOperationException。

I don't think it will work when the Forms are created on different threads, but you would normally do this by setting the Form's TopLevel property to False and then adding it to the tab page control (or any other parent control).

Edit: You also need to set the Visible property to True because Forms are hidden by default.

Also, I just tried this and it does work for something like a button created from another thread. But when I did it with a Form, I got an InvalidOperationException.

长亭外,古道边 2024-11-15 23:19:49

您应该能够从 TabPage 上的 Controls 集合中调用 Add。您可能需要相应地设置 AnchorDock 属性,以便控件填充整个表面(假设这就是您想要的)。

我不认为从另一个线程创建控件是一个好的途径。我确信只要使用适当的同步机制等,您就完全有能力使这种切换线程安全。但是,所有 UI 元素都具有线程关联性,这意味着一旦创建该 UI 元素,它就属于创建线程。简单地创建(只是构造函数调用)可能不会有任何问题,但我采取的规则是将所有 UI 元素逻辑严格保留在 UI 线程上。

You should be able to just call Add from the Controls collection on the TabPage. You will probably want to set the Anchor and Dock properties accordingly so that the control fills the whole surface (assuming that is what you want).

I do not think creating the control from another thread is a good route though. I am sure you are quite capable of making this hand off thread-safe as far as using the appropriate synchronization mechanisms and whatever. But, all UI elements have thread-affinity which means that once that UI element is created it belongs to the creating thread. You may not have any issues with simply creating (just a constructor call), but I take the rule of keeping all UI element logic on the UI thread quite literally and strictly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文