簡體   English   中英

Winforms、數據綁定、列表框和文本框

[英]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; }
}

我嘗試覆蓋MyItemToString()以便它可以使用它。 但這也行不通。

有人願意試一試嗎?

其中一個最簡單的方法,我想,會使用BindingSource ,將其設置為ListBox.DataSource屬性為您BindingSource設計。

  1. 在您的表單上放置一個BindingSource
  2. 將您的ListBox.DataSource屬性設置為您的BindingSource
  3. 像實際操作一樣設置ValueMemberDisplayMember屬性;
  4. 為您的TextBox控件創建DataBinding ,並使用您的BindingSource作為源,使用您的MyItem.Comment屬性;
  5. 將您的List(Of MyItem)分配給您的Binding.DataSource屬性;
  6. 您的 TextBox 應遵循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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM