Winforms、数据绑定、列表框和文本框 [英] Winforms, databinding, Listbox and textbox

查看:23
本文介绍了Winforms、数据绑定、列表框和文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的屏幕上有一个列表框 (MyListBox) 和一个文本框 (MyTextBox).

I have a ListBox (MyListBox) on my screen, and a Textbox (MyTextBox).

ListBox 中填充了一个 List(Of T),都是自定义项.

The ListBox is filled with a List(Of T), which are all custom items.

现在我尝试这样做:

ListBox 的数据源是 List(Of T).

The ListBox' datasource is the List(Of T).

现在,当项目更改时,我希望将文本框更新为列表框中所选项目的特定属性.

Now when an Item changes I want the textbox to be updated to a particular property of the selected item in my ListBox.

在代码中这意味着:

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 时,它可以完美运行.

this does not work. But when I bind to SelectedValue instead of SelectedItem it works perfectly.

_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() 以便它使用它.但这也行不通.

I tried overriding the ToString() in MyItem so that it would use that. But that doesn't work either.

有人愿意试一试吗?

推荐答案

我想,最简单的方法之一是使用 BindingSource,将其设置为 ListBox.DataSource 属性到您的 BindingSource 关于设计.

One of the easiest way, I guess, would be to use a BindingSource, setting it as the ListBox.DataSource property to your BindingSource on design.

  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.
  1. Drop a BindingSource on your form;
  2. Set your ListBox.DataSource property to your BindingSource;
  3. Set your ValueMember and DisplayMember properties just like you're actually doing;
  4. Make your DataBinding for your TextBox control, and use your BindingSource as the source, using your MyItem.Comment property;
  5. Assign your List(Of MyItem) to your Binding.DataSource property;
  6. Your TextBox should follow the CurrencyManager.CurrentItem's Comment property, that is, the currently ListBox.SelectedItem.

实际上,您可能需要实施 INotifyPropertyChanged 接口使其正常工作.

Indeed, you would perhaps need to implement the INotifyPropertyChanged interface to make it work properly.

但如果这一切都与 SelectValue 完美配合,为什么不直接使用它?

But if this all work perfect with the SelectValue, why don't you just use it?

这篇关于Winforms、数据绑定、列表框和文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆