Целью здесь является использование BindingSource + Object в качестве источника данных и TextBox для отображения значения свойства объекта.привязка текстового поля к объекту с помощью bindingsource не refreshing
Проблема, с которой я столкнулся, заключается в том, что TextBox не отражает изменения значений свойств базового объекта.
Как говорят китайцы, одна фотография равна тысячам слов, поэтому ниже демо-кода, который демонстрирует проблему, с которой я столкнулся.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.CompilerServices;
namespace TextBoxDataSourceBindingDemo
{
public partial class Form1 : Form
{
private BindingSource dsSource;
private BindingDemoClass bDemoClass;
public Form1()
{
InitializeComponent();
bDemoClass = new BindingDemoClass();
dsSource = new BindingSource();
bDemoClass.BindingName = "DemoBinding";
this.textBox1.DataBindings.Add(new Binding("Text", dsSource, "BindingName",true,DataSourceUpdateMode.OnPropertyChanged));
}
private void btnAssignDataSource_Click(object sender, EventArgs e)
{
//Setting the datasource is not enough to
//update the related textbox
//refresh must be explicity called ?
dsSource.DataSource = bDemoClass;
dsSource.ResetBindings(true);
}
private void btnChangePropertyValue_Click(object sender, EventArgs e)
{
//Here after setting the property value
//the textbox should be update with the new value; correct ?
bDemoClass.BindingName = "DemoBinding2";
}
}
//Demo class used as datasource
public class BindingDemoClass : INotifyPropertyChanged
{
private string _BindingName = String.Empty;
public string BindingName
{
get { return _BindingName; }
set
{
if (!String.Equals(_BindingName, value))
{
_BindingName = value;
NotifyPropertyChanged();
}
}
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
Так при нажатии на кнопку btnAssignDataSource текстовое поле обновляется. Я бы ожидал, что при изменении связанного свойства (btnChangePropertyValue) это изменение будет отражено в текстовом поле.
Да, я получаю тот же результат. – Yiorgos
Можете ли вы попытаться сбросить привязку после вызова события btnChangePropertyValue. – sagar
Да пробовал, что с самого начала не работал. Единственный способ получить эту работу - удалить привязку из текстового поля и добавить ее снова. Смена события события, так что часть работает. Возможно, что-то связано со связыванием с текстовым полем. – Yiorgos