我需要TextBox来反映数据绑定字符串的变化。我尝试了以下代码:
public partial class Form1 : Form
{
string m_sFirstName = "Brad";
public string FirstName
{
get { return m_sFirstName; }
set { m_sFirstName = value; }
}
public Form1()
{
InitializeComponent();
textBox1.DataBindings.Add("Text", this, "FirstName");
}
private void buttonRename_Click(object sender, EventArgs e)
{
MessageBox.Show("before: " + FirstName);
FirstName = "John";
MessageBox.Show("after: " + FirstName);
}
}
启动应用程序后,textBox1正确填充了Brad。 我点击了按钮,它将FirstName重命名为“John”(第二个消息框确认了它)。 但是textBox1仍然充满了布拉德,而不是约翰。为什么?什么使这项工作?
答案 0 :(得分:3)
一种方法是添加一个FirstNameChanged
事件,然后数据绑定将挂钩。然后在更改属性时引发事件,它将重新绑定。例如:
using System;
using System.Drawing;
using System.Windows.Forms;
public class DataBindingTest : Form
{
public event EventHandler FirstNameChanged;
string m_sFirstName = "Brad";
public string FirstName
{
get { return m_sFirstName; }
set
{
m_sFirstName = value;
EventHandler handler = FirstNameChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
public DataBindingTest()
{
Size = new Size(100, 100);
TextBox textBox = new TextBox();
textBox.DataBindings.Add("Text", this, "FirstName");
Button button = new Button
{
Text = "Rename",
Location = new Point(10, 30)
};
button.Click += delegate { FirstName = "John"; };
Controls.Add(textBox);
Controls.Add(button);
}
static void Main()
{
Application.Run(new DataBindingTest());
}
}
可能有其他方法(例如使用INotifyPropertyChanged
) - 我不是任何方式的数据绑定专家。
答案 1 :(得分:3)
DataBinding没有反映您的更改的原因是因为您绑定了一个简单的System.String对象,该对象尚未设计为在修改时抛出事件。
所以你有两个选择。一种是在按钮的Click事件中重新绑定值(请避免!)。另一种是创建一个将实现INotifyPropertyChanged的自定义类:
public partial class Form1 : Form
{
public Person TheBoss { get; set; }
public Form1()
{
InitializeComponent();
TheBoss = new Person { FirstName = "John" };
textBox1.DataBindings.Add("Text", this, "TheBoss.FirstName");
}
private void button1_Click(object sender, EventArgs e)
{
TheBoss.FirstName = "Mike";
}
public class Person : INotifyPropertyChanged
{
private string firstName;
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
NotifyPropertyChanged("FirstName");
}
}
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
INotifyPropertyChanged文档:MSDN
答案 2 :(得分:0)
您需要在按钮单击时再次执行数据绑定,否则它只在表单实例化时运行一次。
要添加:上述声明不适合该要求。它仍然有效(参见下面的代码),但是通过事件处理来破坏绑定的目的。
Binding binding1; //binding instance
public Form1()
{
InitializeComponent();
binding1 = textBox1.DataBindings.Add("Text", this, "FirstName"); //assign binding instance
}
private void buttonRename_Click(object sender, EventArgs e)
{
MessageBox.Show("before: " + FirstName);
FirstName = "John";
textBox1.DataBindings.Remove(binding1); //remove binding instance
binding1 = textBox1.DataBindings.Add("Text", this, "FirstName"); //add new binding
MessageBox.Show("after: " + FirstName);
}