1
현재 포커스가있는 TextBox의 데이터 바인딩 된 개체를 변경하면 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));
}
}
}
이 감사를 작동합니다. BindingSource.ResetBindings가 나를 위해이 작업을 수행하기를 바랬습니다. 내 애플 리케이션에서 수동으로 통증이 화면에있는 모든 텍스트 상자를 지워야 할 것입니다. – kbeal2k
@ kbeal2k 나는 그런 데이터 소스를 끊임없이 바꾸는 것은 드문 일이라고 생각한다. 이 전략을 다시 생각해 볼 수 있습니다. – LarsTech
_data.Value 직접 변경하고 데이터 원본을 변경하지 않은 경우에도이 문제가 발생합니다. – kbeal2k