C#中数据绑定的简单例子
数据绑定允许将控件的属性和数据链接起来——控件属性值发生改变,会导致数据跟着自动改变。
数据绑定还可以是双向的——控件属性值发生改变,会导致数据跟着自动改变;数据发生改变,也会导致控件属性值跟着自动改变。
1、数据绑定的三个关键点
实现数据绑定的三个关键步骤
- ①创建绑定数据
- ②控件绑定数据(重点是:数据绑定的语法)
- ③数据更新的通知方法(重点是:属性更改通知事件的实现)
数据绑定的语法
Control.DataBindings.Add(“控件的属性名”,数据源,”数据源的属性名”);
下面通过一个例子——通过按键控制三个控件状态,来演示具体如何进行数据绑定。
2、实现效果
3、整体的文件结构
4、Data.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace videoFromBili_474458694
{internal class Data : INotifyPropertyChanged{private bool valveState;public bool ValveState{get { return valveState; }set{valveState = value;ValveText = valveState ? "水泵已开启" : "水泵已关闭";ValveColor = valveState ? Color.Green :Color.Red;OnPropertyChanged(nameof(ValveState));//这一句保证数据绑定是双向的}}public string ValveText { get; set; }public Color ValveColor { get; set; }//③数据更新的通知方法(重点是:属性更改通知事件的实现)public event PropertyChangedEventHandler PropertyChanged;protected virtual void OnPropertyChanged(string propertyName){if (PropertyChanged != null){PropertyChanged(this, new PropertyChangedEventArgs(propertyName));}}}
}
5、Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;namespace videoFromBili_474458694
{public partial class Form1 : Form{//①创建绑定数据Data data = new Data(); public Form1(){InitializeComponent();//②控件绑定数据label1.DataBindings.Add("Text",data, "ValveState");button1.DataBindings.Add("BackColor", data, "ValveColor");textBox1.DataBindings.Add("Text", data, "ValveText");}private void button_Open_Click(object sender, EventArgs e){data.ValveState = true;}private void button_Close_Click(object sender, EventArgs e){data.ValveState = false;}}
}
参考
C#上位机数据绑定细节(实用干货分享)_哔哩哔哩_bilibili
【实战】Winform专题实战训练-数据绑定 B0951_哔哩哔哩_bilibili
C#winform数据绑定_winform bind-CSDN博客