我的窗口中有一些文本框,点击btn_add后它们的内容将被添加到Observable Collection中,然后将成为dg_VoucherDetail的源。 问题是: 当我第一次使用它时一切都很好,但第二次它只是替换旧的Observable Collection,除了向旧的Collection添加新项目, 对于编辑部分,Collection中没有要搜索和编辑的项目。 这是代码:
assert_predicate flash[:error], :nil?
答案 0 :(得分:0)
这是一个简单的片段,它会更新"如果条目存在于集合中,则为条目。这个片段有硬编码的东西,但是使它变得动态应该是微不足道的。
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;
namespace UpdateObservableCollection_47291451
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DataGrid dg = new DataGrid();
Button btn = new Button();
ObservableCollection<VoucherDetail> datasource = new ObservableCollection<VoucherDetail>();
public MainWindow()
{
InitializeComponent();
dg.Height = 200;
dg.Width = 500;
MainGrid.Children.Add(dg);//add DataGrid to page
btn.Content = "Click me";
btn.Click += Btn_Click;
btn.Height = 25;
btn.Width = 50;
MainGrid.Children.Add(btn);//add button to page
dg.ItemsSource = datasource;//bind grid to data
//create initial data records
for (int i = 0; i < 5; i++)
{
datasource.Add(new UpdateObservableCollection_47291451.VoucherDetail { Credit = i, Debit = i, DefinitiveID = i, LedgerID = i });
}
}
private void Btn_Click(object sender, RoutedEventArgs e)
{
//if a record with DefinitiveID of 1 exist, then update the entry
if (datasource.FirstOrDefault(p => p.DefinitiveID == 1) != null)
{
datasource.First(p => p.DefinitiveID == 1).Credit = 1234;
dg.Items.Refresh();
}
else
{
datasource.Add(new UpdateObservableCollection_47291451.VoucherDetail { DefinitiveID = 99, Credit = 99, Debit = 99, LedgerID = 99 });
}
}
}
internal class VoucherDetail
{
public decimal LedgerID { get; set; }
public decimal DefinitiveID { get; set; }
public decimal Debit { get; set; }
public decimal Credit { get; set; }
}
}