更改绑定对象在聚焦时不会更新TextBox

时间:2014-08-27 22:06:00

标签: c# winforms data-binding

如果我更改当前聚焦的TextBox的数据绑定对象,则TextBox不会显示新值。

给定一个带有按钮,标签和文本框的简单表单,使用下面的代码。如果用户更改了文本框值和选项卡,则文本不会重置以匹配新绑定的值(在此示例中为20)。但是,如果我通过按钮单击事件触发更新,则文本框会更新。

当属性更改事件在此处触发时,如何获取文本框值以显示新绑定的值(20)?

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace BindingsUpdate
{
    public partial class Form1 : Form
    {
        private MyData _data;
        private System.Windows.Forms.BindingSource myDataBindingSource;   
        public Form1()
        {
            InitializeComponent();
            this.components = new System.ComponentModel.Container();
            this.myDataBindingSource = new System.Windows.Forms.BindingSource(this.components);
            this.myDataBindingSource.DataSource = typeof(BindingsUpdate.MyData);
            this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.myDataBindingSource, "Value", true));
            this.label1.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.myDataBindingSource, "Value", true));

            _data = new MyData () { Value = 10.0};

            this.myDataBindingSource.DataSource = _data;

            _data.PropertyChanged += Data_PropertyChanged;
        }

        private void Data_PropertyChanged (object sender, PropertyChangedEventArgs e)
        {
            RefreshData ();
        }

        private void RefreshData ()
        {
            _data.PropertyChanged -= Data_PropertyChanged;
            _data = new MyData () {Value = 20.0};
            this.myDataBindingSource.DataSource = _data;

            //these don't seem to do anything..
            this.myDataBindingSource.ResetBindings(false);
            this.myDataBindingSource.ResetCurrentItem();

            _data.PropertyChanged += Data_PropertyChanged;
        }

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

    public class MyData : INotifyPropertyChanged
    {
        private double _value;

        public double Value
        {
            get { return _value; }
            set
            {
                if (value.Equals(_value)) return;
                _value = value;
                OnPropertyChanged("Value");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

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

1 个答案:

答案 0 :(得分:1)

您的DataBindings已经过时,因为您替换了现有的DataSource。

尝试清除并重新添加:

this.textBox1.DataBindings.Clear();
this.textBox1.DataBindings.Add(new Binding("Text", this.myDataBindingSource, "Value", true));