问题描述
我有一段代码将文本框绑定到Object属性,如下所示:
txtCreator.DataBindings.Add("Text",this.Application,"Creator");
txtName.DataBindings.Add("Text","Name");
txtOrganization.DataBindings.Add("Text","Organization");
txtGuid.DataBindings.Add("Text","UniqueID");
txtDescription.DataBindings.Add("Text","Description");
该类实现INotifyPropertyChanged,但它们都与“名称”之一分开工作。无论我做什么,都不会从UI绑定到对象。但是,如果我将属性名称更改为其他名称。例如
txtName.DataBindings.Add("Text","AnotherName")
并更改属性名称,它将在第一次运行!!!名为Name的属性是否存在某些特殊情况,这意味着它将无法工作。我过去了,并且已经启动并运行了,但是这很疯狂。
好的,我创建了一个独立的小例子,证明了我的观点。这是一个实现INotifyPropertyChanged的类:
class TestClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
get => _name;
set
{
// Will never fire from binding
_name = value;
ValueUpdated();
}
}
// This is here because a property called Name doesn't bind correctly. Absolutely INSANE!!!
public string BindingName
{
get => _name;
set
{
_name = value;
ValueUpdated();
}
}
protected void ValueUpdated([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
}
}
这是表单代码:
public partial class Form1 : Form
{
internal TestClass TestObject { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender,EventArgs e)
{
this.TestObject = new TestClass();
this.TestObject.Name = "Hello";
// Name won't work
txtName.DataBindings.Add("Text",this.TestObject,"Name");
// Binding Name will
//txtName.DataBindings.Add("Text","BindingName");
}
}
使用原样的代码,集将永远不会在TestClass上名为Name的属性中触发,但是只需取消注释使用BindingName属性的行即可触发集。如您所见,“名称”有效但名称由于某种原因而无效。
解决方法
看起来像是对的,名称属性的特例。