如何绑定动态创建的TextBox?酒店价格列表绑定问题
酒店价格列表双向数据绑定问题
我正在开发酒店价格列表功能,拥有数量不固定的日期列表和酒店房型列表,需动态生成对应控件,以下是实现代码:
private void CreateControls() { var colIndex = 0; var vrsteSoba = _Presenter.VrstaSobeDto.ToArray(); foreach (var bindingItem in vrsteSoba) { var lbl = new Label() { Width = LABEL_WIDTH, Height = LABEL_HEIGHT - 5, Left = 10, Top = 30 + colIndex * (EDIT_BOX_HEIGHT + SPACE_BETWEEN_CONTROL), Text = bindingItem }; _dataPanel.Controls.Add(lbl); colIndex++; } int a = 1; foreach (var date in _Presenter.CeneTarifa) { int y = 0; var panel = new Panel { Height = PANEL_HEIGHT * (vrsteSoba.Length-4), Width = EDIT_BOX_WIDTH, Left = a * (EDIT_BOX_WIDTH + SPACE_BETWEEN_CONTROL + 50), Top = 5 }; _dataPanel.Controls.Add(panel); var label = new Label { Height = EDIT_BOX_HEIGHT, Location = new Point(0, 10), Text = date.Datum, Margin = new Padding(0) }; panel.Controls.Add(label); int index = 0; foreach (var item in date.VrstaSobeCena) { var box = new TextBox(); panel.Controls.Add(box); box.Height = EDIT_BOX_HEIGHT; box.Width = EDIT_BOX_WIDTH; box.Location = new Point(0, 30 + y * (EDIT_BOX_HEIGHT + SPACE_BETWEEN_CONTROL)); box.DataBindings.Add(new Binding(nameof(box.Text), date, date.Cena[index].Cena1)); y++; index++; } ++a; } _dataPanel.AutoScroll = true; }
以下是界面效果:
我现在遇到了数据绑定的问题,需要为每个TextBox实现价格的双向绑定,但陷入了困境。
我曾尝试绑定到属性名,但所有文本框都会获得相同的值;尝试通过索引绑定值时,会报错:Cannot bind to the property or column 34 on the DataSource. Parameter name: dataMember
以下是用于填充Presenter中模型的代码:
private void FillCenePoTarifi() { var sobeArr = VrstaSobeDto.ToArray(); foreach (var datum in Datumi) { var dictionary = new Dictionary<string, decimal>(); var cene = new List<Cena>(); foreach (var item in sobeArr) { var tarif = _Tarife.Where(x => x.SifTarife == item).FirstOrDefault(); if (tarif != null) _SastavTarife = HotelierServerLocal.Default.TarifaViewBlo.GetSastaveTarife(tarif.IdTarife); //proveriti ovu logiku var cena = _SastavTarife.Where(x => x.Cena1 != 0).Select(c => c.Cena1).FirstOrDefault(); cene.Add(new Cena { Cena1 = cena.ToString()}); dictionary.Add(item, cena); } var model = new CenePoTarifi { Datum = datum, VrstaSobeCena = dictionary, Cena = cene }; CeneTarifa.Add(model); } }
最后是使用的模型类:
public class CenePoTarifi{ public Dictionary<string, decimal> VrstaSobeCena { get; set; } = new Dictionary<string, decimal>(); public string Datum { get; set; } private List<Cena> _Cena; public List<Cena> Cena { get => _Cena; set { _Cena = value; NotifyPropertyChanged("Cena"); } } public class Cena { private string _Cena1; public string Cena1 { get => _Cena1; set { _Cena = value; NotifyPropertyChanged("Cena1"); } } }
有人能给出解决方案吗?
内容的提问来源于stack exchange,提问作者Zeljko Jerkovic
相关产品推荐
相关产品推荐

