WPF数据绑定:https://blog.csdn.net/weixin_42274148/article/details/104875176
1、界面效果;
2、工程结构;
3、Data.cs
using System;
using System.Collections.Generic;
using System.ComponentModel; //需要导入此空间
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestBinding
{
class Data : INotifyPropertyChanged //.net定义的接口
{
private int sum;
public int Sum
{
get
{
return this.sum;
}
set
{
this.sum = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Sum")); //触发事件
}
}
}
public event PropertyChangedEventHandler PropertyChanged; //实现接口
}
}
4、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;
namespace TestBinding
{
public partial class Form1 : Form
{
private Data myData = new Data();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myData.Sum = 0;
textBox1.DataBindings.Add("Text", myData, "Sum") ;
}
private void button1_Click(object sender, EventArgs e)
{
myData.Sum++;
}
}
}