【发布时间】:2017-08-24 20:24:58
【问题描述】:
我是 WPF 的新手,我在绑定和 itemsource 方面确实面临许多问题,并开始讨厌这种荒谬的绑定控件的方式,尤其是使用 dataGrid 我实际上习惯于使用 winforms 进行编程,无论如何我有一个 textBox项目 ID 并使用 dataGrid Rows 检查它,如果其中一个行具有相同的 ID,然后根据我已经在其他文本框中(如 txtQty 和 txtBuyPrice)中提供的值更新其列,如果没有具有相同 ID 的行,则只需像下面的代码一样添加新行
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
if (ItemID != "" && txtQty.Text != "" && int.Parse(txtQty.Text) > 0)
{
for (int i = 0; i < dataGridView.Items.Count; i++)
{
if (int.Parse(ItemID) == int.Parse((dataGridView.Items[i] as DataRowView).Row.ItemArray[0].ToString()))
{
(dataGridView.SelectedCells[3].Column.GetCellContent(i) as TextBlock).Text = int.Parse(txtQty.Text) +
int.Parse((dataGridView.SelectedCells[3].Column.GetCellContent(i) as TextBlock).Text).ToString();
(dataGridView.SelectedCells[4].Column.GetCellContent(i) as TextBlock).Text = txtBuyPrice.Text;
(dataGridView.SelectedCells[5].Column.GetCellContent(i) as TextBlock).Text = string.Format("{0:n2}",
double.Parse((dataGridView.SelectedCells[0].Column.GetCellContent(i) as TextBlock).Text) *
double.Parse((dataGridView.SelectedCells[0].Column.GetCellContent(i) as TextBlock).Text));
txtSearch.Focus();
return;
}
}
object date;
if (dtpExpireDate.IsEnabled == true)
date = dtpExpireDate.Text;
else
date = null;
var data = new AddItems { ID = ItemID, ItemName = txtItemName.Text,Date=date,
Qty=txtQty.Text,BuyPrice=txtBuyPrice.Text,
TotalPrice=string.Format("{0:n2}",(int.Parse(txtQty.Text)*double.Parse(txtBuyPrice.Text)).ToString())};
dataGridView.Items.Add(data);
ClearItem();
txtSearch.Focus();
}
}
参考数据来自以下函数
public class AddItems
{
public string ID { get; set; }
public string ItemName { get; set; }
public object Date { get; set; }
public string Qty { get; set; }
public string BuyPrice { get; set; }
public string TotalPrice { get; set; }
}
当 ItemID 和 dataGrid 行之间的 If 条件比较时出现异常,并且当 dataGrid 不为空并且旁边已经有一行时,如果 dataGrid 为空,则新行将正常添加并且异常是(对象引用未设置为实例对象),并且此异常指向第二个 if 语句,它在 ItemID 和 dataGrid 值之间进行比较。 所以请我已经花了 20 个小时来解决问题,但我没有得到很好的答案。
【问题讨论】:
-
WPF 是一种很好的开发方式,但您必须使用 MVVM 才能实现数据绑定的最大效率。
-
@DimosK 我真的需要尽快开发这个项目,所以我没有时间学习 MVVM,但如果你有课程或书籍,请提及跨度>
-
网上有很多东西要读。反正。如何绑定数据网格?你有清单吗?
-
@DimosK 没有绑定我只是从文本框中获取值并通过 AddItems 类将其放入 dataGrid 中,我不知道这是否正确,因为我不熟悉绑定事情,如果不正确,我应该怎么做才能让事情继续写下去,我真的很困惑。
-
您目前使用的是 WPF 还是 WinForms?完整的数据网格类型名称是什么?