本例中,在(二)的基础上,给用户控件添加一个新的属性。用于返回一个字符串。
全部代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace WindowsControlLibrary1
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private string newTextValue;//定义一个私有属性
public string _newTextValue
{
get { return newTextValue; }
set { newTextValue = value; }
}
private void UserControl1_Load(object sender, EventArgs e)
{
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
this.textBox1.TextChanged += new System.EventHandler(this.UserControl1_TabIndexChanged);
}
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
int ch = e.KeyChar;
if (((ch >= 48) && (ch <= 57) || ch == 8 || ch == 13) == false)
{
e.Handled = true;
}
}
private void UserControl1_TabIndexChanged(object sender, EventArgs e)
{
this.newTextValue ="你输入的值是:"+this.textBox1.Text;
}
}
}
调用程序的全部代码 :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.Text = this.userControl11._newTextValue;
}
}
}
欢迎访问我的blog