你真的是指“字典”吗? Winform绑定与列表(IList
/IListSource
)一致,但不包含字典。此外,ListView
并不像其他控件那么容易绑定。
除此之外,它应该纯粹使用映射名称 - 我会尝试做一个简单的例子...
用Northwind的基本示例编辑;请注意,数据上下文理想情况下应该不会很长;你可能也想看看东西像仓库的实现,而不是直接绑定:
using System;
using System.Windows.Forms;
using SomeNamespaceWithMyDataContext;
static class Program
{
[STAThread]
static void Main() {
MyDataContext ctx = new MyDataContext();
BindingSource custs = new BindingSource() {
DataSource = ctx.Customers};
BindingSource orders = new BindingSource {
DataMember = "Orders", DataSource = custs};
Button btn;
using (Form form = new Form
{
Controls = {
new DataGridView() {
DataSource = orders, DataMember = "Order_Details",
Dock = DockStyle.Fill},
new ComboBox() {
DataSource = orders, DisplayMember = "OrderID",
Dock = DockStyle.Top},
new ComboBox() {
DataSource = custs, DisplayMember = "CompanyName",
Dock = DockStyle.Top},
(btn = new Button() {
Text = "Save", Dock = DockStyle.Bottom
}), // **edit here re textbox etc**
new TextBox {
DataBindings = {{"Text", orders, "ShipAddress"}},
Dock = DockStyle.Bottom
},
new Label {
DataBindings = {{"Text", custs, "ContactName"}},
Dock = DockStyle.Top
},
new Label {
DataBindings = {{"Text", orders, "RequiredDate"}},
Dock = DockStyle.Bottom
}
}
})
{
btn.Click += delegate {
form.Text = "Saving...";
ctx.SubmitChanges();
form.Text = "Saved";
};
Application.Run(form);
}
}
}
顺便说一句 - 注意语法:
DataBindings = {{"Text", orders, "ShipAddress"}}
等同于:
someTextBox.DataBindings.Add("Text", orders, "ShipAddress");
(因为这是一个常见问题,所以我只添加这个)
重新评论 - 我会添加一些文本字段... – 2009-05-19 11:16:23