.Net - 动态地将控件从类添加到表单 [英] .Net - Dynamically add Control from Class to Form

查看:105
本文介绍了.Net - 动态地将控件从类添加到表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向Main(单个)表单添加一些控件但没有成功。

从表单中没有问题,从Sub New()或Load()添加它但是从另一类我无法做到。下面是一个示例;



我正在尝试使用一些特殊函数创建一个.dll,这就是为什么我需要动态地将一些控件添加到主窗体



简单示例;



I am trying to add some controls to the Main(single) Form but without success.
From the Form within thats no problem, adding it from Sub New() or Load() but from another Class i am not able to do it. An example here below;

I am trying to make a .dll with some special functions on it, thats why i need to add dynamically some Controls to the Main Form

Simple Example;

Public Class Form1

End Class


<System.Runtime.InteropServices.ComVisibleAttributte(True)> _
Public Class Example : Inherits UserControl

Sub New()
        Dim pan As New Panel
        With pan
            .BackColor = Color.Blue
            .Size = New Size(33, 33)
            .Location = New Point(10, 10)
            .Visible = True
            Form1.Controls.Add(pan)
            ' also tried
            ' Me.Controls.Add(pan)
        End With
End Sub
End Class

推荐答案

不是 Form1.Controls.Add(pan),但只是 Controls.Add(pan)。另请参阅我的评论。



Form1 是某种类型,的基本类型。该类型没有您能够调用的属性 Control ,但其实例具有。这是一个实例属性,而不是静态属性。



最后,我想出了这个问题:问题是你不了解基础知识;在这种情况下,这是对类型及其实例(对象)的理解。在进行UI开发并独立进行之前,还有很多需要了解的内容。我可以建议退一步学习编程的基础知识,包括OOP。为此,我建议您在简单的控制台应用程序上进行练习。



-SA
Not Form1.Controls.Add(pan), but just Controls.Add(pan). See also my comments.

Form1 is some type, the base type for Example. The type does not have the property Control you would be able to call, but its instance has. This is an instance property, not static property.

Finally, I figured this out: the problem is that you don''t understand the very basics; in this case, this is understanding of types and their instances (objects). There is a lot more to understand before you can get to UI development and proceed independently. I can advise to step back and learn basics of programming, including OOP. For that, I would recommend doing your exercises on simple console applications.

—SA


Form1类没有成员控件。如果它继承了System.Windows.Forms.Form,你仍然无法像你那样添加控件。您必须将它添加到Form1的实例。



从与Form1相同的程序集中,您可以尝试:

Form1 class does not have the member Controls. If it inherited System.Windows.Forms.Form, you still cannot add a control like you did. You must add it to an instance of Form1.

From the same assembly as the Form1 you could try this:
My.Forms.Form1.Controls.Add(something)





来自不同的集会,你只需要制作Form1的实例可用。



From a different assembly, you just have to make the instance of Form1 available to it.


这篇关于.Net - 动态地将控件从类添加到表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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