Если я изменил объект привязки привязанного в данный момент 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));
}
}
}
Ваши DataBindings устарели, поскольку вы заменили существующий DataSource.
Попробуйте очистить и добавить их обратно:
this.textBox1.DataBindings.Clear();
this.textBox1.DataBindings.Add(new Binding("Text", this.myDataBindingSource, "Value", true));