【发布时间】:2016-06-20 11:27:29
【问题描述】:
我在 WinForm 中找到了数据绑定:
BindingSource bs = new BindingSource();
test t = new test ();
t.Foo = "Ahmet";
bs.DataSource = t;
label1.DataBindings.Add(new Binding("Text", bs, "Foo", false, DataSourceUpdateMode.OnPropertyChanged));
这可行,但我需要更复杂的数据绑定。 我有区域、课桌课程。我从 db 获取数据并创建 List 对象。所有区域都有很多桌子。
我尝试了以下操作,但它不起作用。按钮文本为空。如何使用数据绑定?
BindingSource bs = new BindingSource();
foreach (Area area in areaList)
{
Button btn = new Button();
btn.AutoSize = false;
btn.Width = 100;
btn.BringToFront();
btn.Height = 35;
btn.Font= new Font("Arial", 16, FontStyle.Bold);
btn.BackColor = Color.White;
btn.FlatStyle = FlatStyle.Flat;
btn.TextAlign = ContentAlignment.MiddleCenter;
btn.Margin = new Padding(3,5,3,5);
btn.DataBindings.Add(new Binding("Text", bs,"Name",false, DataSourceUpdateMode.OnPropertyChanged));
btn.Click += new EventHandler(btnAreaClick);
fpnlAreas.Controls.Add(btn);
}
区域分类
public class Area : INotifyPropertyChanged
{
private string _id;
private string _name;
private List<Table> _table;
public event PropertyChangedEventHandler PropertyChanged;
public List<Table> ListOfTable
{
get { return _table; }
set { _table = value;
OnPropertyChanged("ListOfTable");
}
}
public string Name
{
get { return _name; }
set { _name = value;
OnPropertyChanged("Name");
}
}
public string Id
{
get { return _id; }
set { _id = value;
OnPropertyChanged("Id");
}
}
public Area()
{
ListOfTable = new List<Entity.Table>();
}
protected virtual void OnPropertyChanged(string Property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(Property));
}
}
}
课桌课
public class Table
{
private string _id;
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Id
{
get { return _id; }
set { _id = value; }
}
public Table()
{
ListOfBill = new List<Bill>();
}
}
【问题讨论】:
标签: c# winforms data-binding label model-binding