我想在C#窗口窗体应用程序中创建一个用户控件 [英] i want make one user control in C# window form Application

查看:214
本文介绍了我想在C#窗口窗体应用程序中创建一个用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的用户控件中,我想添加 2个标签,2个文本框,2个按钮.
当我在应用程序中使用此控件时.我想使用此 2个文本bo x的值,我也想在我的应用程序中使用2个按钮单击事件,这意味着我希望2个使用 click事件 2按钮在我的应用程序中的位置.是否有可能,然后请提供一些相关示例.这样我就可以理解如何控制我的应用程序.

in my User Control i want to add 2 label ,2 text box,2 button.
when i used this control in my application. i want use value of this 2 text box and also i want use 2 button click event in my application means i want 2 use click event of 2 button in my application.is that possible then please give some related example for that.so i can understand how i can make my control for my application.

推荐答案

您可以将组成控件的属性公开为用户控件的属性,如下所示:
You can expose your constituent control properties as properties of the user control, like this:
public string Text1 {
    get {
        return textBox1.Text;
    }
    set {
        textBox1.Text = value;
    }
}



同样,您可以将文本框的事件公开为UserControl的事件



Similarly, you can expose events the textbox as event of the UserControl

public event EventHandler Button1Click;
protected internal void OnButton1Click(EventArgs args) {
    if (Button1Click != null) {
        Button1Click(this, args);
    }
}

//This event handles Button1's Click event
private void Button1_Click(object sender, EventArgs args) {
    OnButton1Click(args);
}


您的问题分为两部分,所以我分为两部分:
在控件中设置两个公共属性:每个文本框一个.给它们起一个合理的名称,以反映它们包含的数据,而不是它们是文本框,例如"Usename"和"Password".
Your question is in two parts, so I''ll answer it in two parts:
Set up two public Properties in your control: one for each textbox. Give them sensible names, which reflect the data they contain, rather than the fact that they are textboxes, such as "Usename" and "Password".
/// <summary>
/// Gets and sets the Username
/// </summary>
public string Username
    {
    get { return textboxUsername.Text; }
    set { textboxUsername.Text = value; }
    }

这些将在设计器中显示为可以初始化的属性.

在您的控件中创建两个事件,每个按钮一个-再次为它们指定一个明智的名称,例如确定"和取消":

These will then appear in the Designer as Properties that can be initialized.

Create two events in your control, one for each button - again, give them sensible names such as "OK" and "Cancel":

/// <summary>
/// Signals that the OK button was pressed
/// </summary>
public event EventHandler OK;
private void button1_Click(object sender, EventArgs e)
    {
    EventHandler eh = OK;
    if (eh != null)
        {
        eh(this, e);
        }
    }


这篇关于我想在C#窗口窗体应用程序中创建一个用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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