如何动态地将 winform 子窗体嵌入到主 winform 的选项卡控件中?
有没有一种方法可以将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为当在不同线程上创建表单时它不会起作用,但通常可以通过将表单的 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.
您想要多文档界面 (MDI) 标签页浏览之类的功能吗?
Do you want something like Multi Document Interface (MDI) tab page browsing?
您应该能够从
TabPage
上的Controls
集合中调用Add
。您可能需要相应地设置Anchor
和Dock
属性,以便控件填充整个表面(假设这就是您想要的)。我不认为从另一个线程创建控件是一个好的途径。我确信只要使用适当的同步机制等,您就完全有能力使这种切换线程安全。但是,所有 UI 元素都具有线程关联性,这意味着一旦创建该 UI 元素,它就属于创建线程。简单地创建(只是构造函数调用)可能不会有任何问题,但我采取的规则是将所有 UI 元素逻辑严格保留在 UI 线程上。
You should be able to just call
Add
from theControls
collection on theTabPage
. You will probably want to set theAnchor
andDock
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.