【发布时间】:2014-08-27 22:05:59
【问题描述】:
如果我更改当前焦点 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));
}
}
}
【问题讨论】:
标签: c# winforms data-binding