【用户自定义控件】 Winform Winform 用户自定义控件

概念:自定义控件只是对系统自带的一些控件就行组合,修改而已。

 

image

 

新建的用户自定义控件类库。一共2个自定义控件。

一个是 label 自定义显示时间控件,名字为  LabelTimer

另一个是btnOpenDiag,点击按钮弹出选择文件框,然后获取文件里的每行内容,并赋值给 ArrayList 属性。

 

 

 

 

 

btnOpenDiag 的部分代码如下

 

重点:重写Text属性,并让Text属性在 设计器中能直接使用。

[Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), Bindable(true)]   //不加这个,无法在设计器中直接设置Text
       public override string Text
       {
           get { return button1.Text; }
            set { button1.Text = value; }
       }

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace shuimo_windowsControls
{
public partial class btnOpenDiag : UserControl
{
public ArrayList txtContextCollection = new ArrayList();
private string text = null;

[Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), Bindable(true)]
public override string Text
{
get { return button1.Text; }
set { button1.Text = value; }
}

public btnOpenDiag()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newD = new OpenFileDialog();
newD.Title = "请选择你的文件";
newD.InitialDirectory = "c:\\";
newD.Filter = "
txt files (*.txt)|*.txt|(All files (*.*))|*.* ";
newD.FilterIndex = 1; //过滤只显示 txt文件,第1个
newD.RestoreDirectory = true;

if (newD.ShowDialog() == DialogResult.OK)
{

//读取文件路径
string name = newD.FileName;


///
///读取文本内容
///
using (StreamReader strRead = new StreamReader(name))
{
string line;

while ((line = strRead.ReadLine()) != null) //空、空格、tab(\t)的都不读
{
if (line.Replace("
", "") != "" && line.Replace("\t", "") != "") //空格,制表符号
{
txtContextCollection.Add(line);
}
}

}

}


}

private void UserControl1_Load(object sender, EventArgs e)
{
Button a = (Button)(this.Controls.Find("
button1", true)[0]);
a.Text = "
初始文本";
}
}
}

原文地址:https://www.cnblogs.com/StudyLife/p/2637213.html