namespace TextBoxDataBindings
{
class Mydata //我的数据类型。注意:这里不能声明为struct,否则数据绑定会无效!
{
public string Value { get; set; }
public DateTime Time { get; set; }
}
static class Program
{
[STAThread]
static void Main()
{
var mydata = new Mydata(); //声明一个用于绑定的对象
var f = new Form() //主窗口
{
Text = "文本框的数据绑定 F1 - 博客",
ClientSize = new Size(292, 266),
KeyPreview = true
};
var textBox1 = new TextBox() //做数据绑定测试。当光标离开此文本框时便会自动刷新绑定数据。
{
Location = new Point(56, 45),
Size = new Size(164, 21)
};
var textBox2 = new TextBox() //不使用绑定,直接修改mydata数据
{
Location = new Point(56, 82),
Size = textBox1.Size
};
var textBox3 = new TextBox() //显示绑定数据的对象mydata.Value的内容
{
Location = new Point(56, 177),
Size = textBox1.Size
};
textBox2.TextChanged += delegate //当文本框2中的文字发生改变时,修改绑定对象mydata
{
mydata.Value = textBox2.Text;
mydata.Time = DateTime.Now;
};
var timer = new Timer() //间隔500毫秒的计时器
{
Interval = 500
};
timer.Tick += delegate //每隔500毫秒,会在文本框3中显示mydata.Value的内容
{
textBox3.Text = mydata.Value != null ? mydata.Value : "<NULL>";
};
f.Controls.Add(textBox1);
f.Controls.Add(textBox2);
f.Controls.Add(textBox3);
f.Load += delegate //在主窗口加载时启动计时器
{
timer.Start();
};
f.KeyUp += delegate(object sernder, KeyEventArgs e)
{
if (Keys.F1 == e.KeyCode)
{
System.Diagnostics.Process.Start("http://hi.baidu.com/wingingbob/blog/item/65652dec1a6b3fd82e2e2165.html");
}
};