如何正确使用DataBindings属性?

时间:2016-04-27 22:15:18

标签: c# winforms data-binding

我试图将Windows窗体标签绑定到变量。当我运行该代码时,lable1显示为50,但是当我使用button1递增时,它不会更改为51.这是我的尝试

    int x = 50;
    public int X
    {
        get { return x; }
        set { x = value; }
    }
    public Form1()
    {
        InitializeComponent();
        label1.DataBindings.Add("Text", this, "X", true, DataSourceUpdateMode.OnPropertyChanged);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        X++;
    }

TIA

3 个答案:

答案 0 :(得分:0)

    int X = 50;

    public Form1() {
        InitializeComponent();
        label1.Text = X.ToString();            
    }

    private void button1_Click(object sender, EventArgs e) {
        X += 1;
        label1.Text = X.ToString();
    }

答案 1 :(得分:0)

您可以将数据放在另一个实现INotifyPropertyChanged的类中,以便通知和更新UI:

public partial class Form1 : Form
{
    DataClass dc;
    public Form1()
    {
        InitializeComponent();
        dc = new DataClass();
        label1.DataBindings.Add("Text", dc, "X", true, DataSourceUpdateMode.OnPropertyChanged);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        dc.X++;
    }
}

public class DataClass : INotifyPropertyChanged
{
    int x = 50;
    public int X
    {
        get { return x; }
        set
        {
            x = value;
            NotifyPropertyChanged("X");
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String info)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }
}

答案 2 :(得分:0)

您的班级表格必须实施INotifyPropertyChanged界面,如下所示:

    public partial class Form1 : Form, INotifyPropertyChanged
    {

        int x = 50;
        public int X
        {
            get { return x; }
            set { x = value; OnPropertyChanged("X"); }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.DataBindings.Add("Text", this, "X", true, DataSourceUpdateMode.OnPropertyChanged);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            X++;
        }
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string property)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
}