[英]Binding TextBox to ListBox SelectedItem does not work
我有一個 Winforms 應用程序,其中有一個列表框和一個文本框。 列表框通過 BindingList 顯示項目列表,並為每個項目顯示項目的屬性名稱。 我想在列表中所選項目的列表旁邊顯示文本框中項目的全名。
為 ListBox 創建 BindingList 沒有問題,但我無法讓 TextBox 工作。 我發現了一個關於 SO ( Binding a TextBox to a ListBox SelectedItem ) 的問題,它舉了一個例子,但我仍然無法讓它工作。 代碼編譯完美,但 TextBox 什么也沒顯示。
這是我寫的代碼:
itemList = new BindingList<Item>();
itemSource = new BindingSource(itemList, null);
lstItems.DataSource = itemSource; // previously I used itemList which also seemed to work?
txtItem.DataBindings.Add(new Binding("Text", itemSource, "Fullname", false, DataSourceUpdateMode.OnPropertyChanged));
Fullname 是 Item class 的屬性,我在上面的示例中嘗試了 BindingList/BindingSource 的各種組合,但似乎沒有任何效果。
我一定錯過了什么,但我看不到什么。 誰能指出我正確的方向? 謝謝!
編輯:為 Pavan Chandaka 添加了項目 class
public class Item
{
private string fullname;
public Item(string fullname)
{
this.fullname = fullname;
}
public string Fullname()
{
return "Fullname: " + fullname;
}
public override String ToString()
{
return Fullname();
}
}
您的Item
class 沒有適當綁定的屬性。
保持簡單並嘗試以下修改的Item
class。
public class Item
{
//PROPERTY
public string Fullname { get; set; }
//CONSTRUCOR
public Item(string fullname)
{
this.Fullname = fullname;
}
//OVERRIDE TOSTRING
public override string ToString() => $"{this.Fullname}";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.