[英]Winforms, databinding, Listbox and textbox
我的屏幕上有一個列表框 ( MyListBox
) 和一個文本框 ( MyTextBox
)。
ListBox 中填充了一個 List(Of T),它們都是自定義項。
現在我嘗試這樣做:
ListBox 的數據源是 List(Of T)。
現在,當項目更改時,我希望將文本框更新為列表框中所選項目的特定屬性。
在代碼中,這意味着:
Me.MyListBox.DisplayMember = "SelectionName"
Me.MyListBox.ValueMember = "Id"
MyTextbox.DataBindings.Add(New Binding("Text", Me._listOfItems, "SelectedItem.Comment", True, DataSourceUpdateMode.OnPropertyChanged))
Me.MyListBox.DataSource = Me._listOfItems
這不起作用。 但是當我綁定到 SelectedValue 而不是 SelectedItem 時,它完美地工作。
_listOfItems
聲明如下:
Dim _listOfItems As List(Of MyItem) = New List(Of MyItem)()
MyItem
在哪里:
public class MyItem
{
public string SelectionName { get; set; }
public int Id { get; set; }
public string Comment { get; set; }
}
我嘗試覆蓋MyItem
的ToString()
以便它可以使用它。 但這也行不通。
有人願意試一試嗎?
其中一個最簡單的方法,我想,會使用BindingSource
,將其設置為ListBox.DataSource
屬性為您BindingSource
設計。
BindingSource
;ListBox.DataSource
屬性設置為您的BindingSource
;ValueMember
和DisplayMember
屬性;TextBox
控件創建DataBinding
,並使用您的BindingSource
作為源,使用您的MyItem.Comment
屬性;List(Of MyItem)
分配給您的Binding.DataSource
屬性;CurrencyManager.CurrentItem
的 Comment 屬性,即當前的ListBox.SelectedItem
。 實際上,您可能需要實現INotifyPropertyChanged
接口才能使其正常工作。
但是,如果這一切都與 SelectValue 完美配合,為什么不直接使用它呢?
下面的代碼顯示了我是如何做的。 我首先將 ListBox DataSource 設置為具有 BindingList 集合的類。 該類實現 IBindingList。 我有兩個要綁定 SelectedItem 的 TextBox。 下面的代碼是我的做法:
lbControl.DataSource = SharepointTestBusinessLayer.Control.ListAll();
lbControl.DisplayMember = "ControlName";
lbControl.SelectedIndex = 0;
scTextBoxControlID.DataBindings.Add("Text", this.lbControl.DataSource, "ControlID");
scTextBoxControlName.DataBindings.Add("Text", this.lbControl.DataSource, "ControlName");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.