在C中,为了创建健壮的用户界面,我们可以使用用户组件和自定义组件功能。关于如何创建用户组件和自定义组件,许多相关的参考书上都会给出说明,这里不再赘述。下面主要给大家演示一下如何在定义好的组件中设置相关属性。示例如下:
上图(图一)是一个非常简单的用户组件,一个form,四个textbox,实现的是模拟ip地址输入框功能。
上图(图二)是将定义的用户组件添加到一个form上,那么对于一个ip地址输入框最起码的应该具有读写数据的功能(即当从输入框中输入数据时,用户组件会得到;当从该组件中设置数据时,会在输入框中显示),它可以通过属性来实现。
若要实现上述功能只需要在定义用户组件时添加一个属性,名称为IPAdddress,代码如下:
public partial class IPinputControl : UserControl
{
public IPinputControl()
{
InitializeComponent();
}
//以下为添加的代码
//定义属性
public string IPAdddress
{
//读数据
get
{
return textBox1.Text + "." + textBox2.Text + "." + textBox3.Text + "." + textBox4.Text;
}
//写数据
set
{
string ipaddress = value;
string[] split = new string[4];
split = ipaddress.Split('.');
if (split.Length == 4)
{
textBox1.Text = split[0];
textBox2.Text = split[1];
textBox3.Text = split[2];
textBox4.Text = split[3];
}
else
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
}
生成解决方案后,将该组件添加到form中(达到图2的效果),选中用户组件,会在其属性栏里看到上面定义的属性IPAdddress,这样就完成了一个用户组件或自定义组件的自定义属性的实现。