[英]Binding doesn't work for properties called Name in C#
我有一段代碼將文本框綁定到 Object 屬性,如下所示:
txtCreator.DataBindings.Add("Text", this.Application, "Creator");
txtName.DataBindings.Add("Text", this.Application, "Name");
txtOrganization.DataBindings.Add("Text", this.Application, "Organization");
txtGuid.DataBindings.Add("Text", this.Application, "UniqueID");
txtDescription.DataBindings.Add("Text", this.Application, "Description");
class 實現了 INotifyPropertyChanged,但除了名為“Name”的那個之外,它們都可以工作。 無論我做什么,它都不會從 UI 綁定回 object。 但是,如果我將屬性名稱更改為其他名稱。 例如
txtName.DataBindings.Add("Text", this.Application, "AnotherName")
並更改屬性名稱,它第一次起作用..! 一個名為 Name 的屬性是否存在一些特殊情況,這意味着它不起作用。 我克服了它並讓它運行起來,但這太奇怪了。
好的,我創建了一個獨立的小例子來證明我的觀點。 這是一個實現 INotifyPropertyChanged 的 class:
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", this.TestObject, "BindingName");
}
}
使用代碼,集合永遠不會在 TestClass 上名為 Name 的屬性中觸發,但是只需取消注釋使用 BindingName 屬性的行並觸發集合。 正如您所看到的,除了“名稱”之外的任何東西都有效,而名稱由於某種原因不起作用。
看起來我是對的,名為 Name 的屬性的特殊情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.