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

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

问题描述

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

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

列表框填充一个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; }
}



我试图重写的ToString() MyItem ,这样它会利用这一点。但是,这也不行。

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

有人关心给它一个尝试一下呢?

Anybody care to give it a try?

谢谢!

-Snakiej

推荐答案

最简单的一种方式,我猜,会是使用 的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. 设置你的 ValueMember 的DisplayMember 属性,就像你实际做;

  4. 请您数据绑定为你的文本框控制,并使用你的的BindingSource 为源,使用 MyItem.Comment 财产;

  5. 分配你的列表(中MyItem)``你 Binding.DataSource`财产;

  6. 您的文本框应该遵循 CurrencyManager.CurrentItem 的Comment属性,也就是当前列表框。的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 yourBinding.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天全站免登陆