关于C#里的数据绑定

fantastic300 2014-03-06 08:56:37
我写了个winform程序 代码如下

public partial class Form1 : Form
{
Person person;
public Form1()
{
InitializeComponent();
person = new Person();
person.Age = 111;
textBox_age.DataBindings.Add("Text", person, "Age");
}

private void button1_Click(object sender, EventArgs e)
{
person.Age = 123;
}
}
class Person
{
public int Age { get; set; }
}
我想现在在button事件里边改变Age的值后,界面上的textBox的值跟着同步改变,我的代码改如何改呢,实现双向绑定。
...全文
109 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
fantastic300 2014-03-07
  • 打赏
  • 举报
回复
简洁明了 谢谢啦
mnxm 2014-03-06
  • 打赏
  • 举报
回复
Form的代码没贴全 重新发个
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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            person = new Person();
            person.Age = 111;
            textBox_age.DataBindings.Add("Text", person, "Age");
        }
        Person person;

        private void button1_Click(object sender, EventArgs e)
        {
            person.Age++;
        }
    }

    public class Person : INotifyPropertyChanged
    {
        private int age;
        public int Age 
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
mnxm 2014-03-06
  • 打赏
  • 举报
回复
        public Form1()
        {
            InitializeComponent();
            person = new Person();
            person.Age = 111;
            textBox_age.DataBindings.Add("Text", person, "Age");
        }
        Person person;

        private void button1_Click(object sender, EventArgs e)
        {
            person.Age++;
        }
    }

    public class Person : INotifyPropertyChanged
    {
        private int age;
        public int Age 
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
mnxm 2014-03-06
  • 打赏
  • 举报
回复
去实现INotifyPropertyChanged接口试试吧

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧