的WinForms数据绑定 [英] WinForms data binding
问题描述
我在数据绑定是新
我有这些类:
public class Foo : List<Bar>
{
public string FooName { get; set; }
}
public class Bar
{
public string BarName { get; set; }
public string BarDesc { get; set; }
}
和我有一个列表<富>
我想在富
项目>组合框和酒吧
在的ListBox
。当我在组合框
更改所选的项目,我想的ListBox
改变。当我在列表框更改所选项目
我想有文本框
充满 BarDesc
。
I would like to have Foo
items in ComboBox
, and Bar
items in ListBox
. When I change selected item in ComboBox
, I want ListBox
to change. When I change selected item in ListBox
I would like to have TextBox
filled with BarDesc
.
继仅供列表框的作品
和组合框
:
comboBox1.DataSource = foos;
comboBox1.DisplayMember = "FooName";
listBox1.DataBindings.Add("DataSource", foos, "");
listBox1.DisplayMember = "BarName";
我不知道现在怎么绑定选择酒吧
在的ListBox
到 TextBox.Text
属性。也许增加了 listBox1中
绑定是不是一个好主意。
I don't now how to bind selected Bar
in ListBox
to TextBox.Text
property. Maybe added binding for listBox1
is not a good idea.
也许我应该做这样的事情:
Maybe I should do something like that:
((CurrencyManager)listBox1.BindingContext[foos]).CurrentChanged += new EventHandler((o, a) =>
{
textBox1.DataBindings.Clear();
textBox1.DataBindings.Add("Text", listBox1.DataSource, "BarDesc");
});
我怎样才能解决我的问题?
How can I resolve my problem?
推荐答案
为使这一切工作,我不得不添加项目
属性设置为富
类。这是两个结合源之间的链接/关系
To make all this work, I had to add the Items
property to the Foo
class. This is the "link/relationship" between the two binding sources.
public partial class Form1 : Form {
public class Foo : List<Bar> {
public string FooName { get; set; }
public Foo(string name) { this.FooName = name; }
public List<Bar> Items { get { return this; } }
}
public class Bar {
public string BarName { get; set; }
public string BarDesc { get; set; }
public Bar(string name, string desc) {
this.BarName = name;
this.BarDesc = desc;
}
}
public Form1() {
InitializeComponent();
List<Foo> foos = new List<Foo>();
Foo a = new Foo("letters");
a.Add(new Bar("a", "aaa"));
a.Add(new Bar("b", "bbb"));
foos.Add(a);
Foo b = new Foo("digits");
b.Add(new Bar("1", "111"));
b.Add(new Bar("2", "222"));
b.Add(new Bar("3", "333"));
foos.Add(b);
//Simple Related Object List Binding
//http://blogs.msdn.com/bethmassi/archive/2007/04/21/simple-related-object-list-binding.aspx
BindingSource comboBoxBindingSource = new BindingSource();
BindingSource listBoxBindingSource = new BindingSource();
comboBoxBindingSource.DataSource = foos;
listBoxBindingSource.DataSource = comboBoxBindingSource;
listBoxBindingSource.DataMember = "Items";
comboBox1.DataSource = comboBoxBindingSource;
comboBox1.DisplayMember = "FooName";
listBox1.DataSource = listBoxBindingSource;
listBox1.DisplayMember = "BarName";
textBox1.DataBindings.Add("Text", listBoxBindingSource, "BarDesc");
}
}
这篇关于的WinForms数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!