C# 用户控件与 Windows 窗体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2299339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:13:24  来源:igfitidea点击:

User Control vs. Windows Form

c#visual-studiowinforms

提问by Arlen Beiler

What is the difference between a user control and a windows form in Visual Studio - C#?

Visual Studio - C# 中的用户控件和 Windows 窗体有什么区别?

采纳答案by Bill Martin

Put very simply:

说得非常简单:

User controls are a way of making a custom, reusable component. A user control can contain other controls but must be hosted by a form.

用户控件是一种制作自定义、可重用组件的方法。用户控件可以包含其他控件,但必须由表单承载。

Windows forms are the container for controls, including user controls. While it contains many similar attributes as a user control, it's primary purpose is to host controls.

Windows 窗体是控件的容器,包括用户控件。虽然它包含许多与用户控件相似的属性,但它的主要目的是承载控件。

回答by Ikke

A windows form is a container for user controls.

Windows 窗体是用户控件的容器。

回答by Hans Passant

They have a lotin common, they are both derived from ContainerControl. UserControl however is designed to be a child window, it needs to be placed in a container. Form was designed to be a top-level window without a parent.

它们有很多共同点,都源自ContainerControl。然而 UserControl 被设计为一个子窗口,它需要被放置在一个容器中。Form 被设计为一个没有父级的顶级窗口。

You can actually turn a Form into a child window by setting its TopLevel property to false:

实际上,您可以通过将 Form 的 TopLevel 属性设置为 false 来将 Form 变成子窗口:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        var child = new Form2();
        child.TopLevel = false;
        child.Location = new Point(10, 5);
        child.Size = new Size(100, 100);
        child.BackColor = Color.Yellow;
        child.FormBorderStyle = FormBorderStyle.None;
        child.Visible = true;
        this.Controls.Add(child);
    }
}

回答by sunnytyra

The biggest difference is form.show gives a different window while usercontrol doesnt have feature like popping up without a parent. Rest things are same in both the controls like beind derived from Scrollablecontrol.

最大的区别是 form.show 给出了一个不同的窗口,而 usercontrol 没有像没有父级弹出的功能。其余的东西在两个控件中都是相同的,比如从 Scrollablecontrol 派生的 beind。