我对以下代码感到头疼。看起来很简单,但我不明白为什么会出错。
这个想法很简单,我只是循环将 DataGirdView 的引用添加到 ViewModel 的属性中。就这样。
但是在我修改了 ViewModel 中的值之后,IEnumerable<ICompanyViewModel> vms
就不会像没有发生一样反映它。我做错了什么?请帮忙。
public void UpdateCompany(IEnumerable<ICompanyViewModel> vms) {
CompanyBindingSource.DataSource = new BindingListView<CompanyViewModel>(vms.ToList());
var lst = new List<DataGridViewRow>();
foreach (DataGridViewRow dgvr in DataGridView1.Rows) lst.Add(dgvr);
foreach (var vm1 in vms) {
foreach (var dgvr in lst) {
var ov = (ObjectView<CompanyViewModel>)dgvr.DataBoundItem;
var vm2 = (ExhibitorViewModel)ov.Object;
if (vm1.ID == vm2.ID) {
vm1.DataGridViewRow = dgvr;
break;
}
}
if (vm1.DataGridViewRow != null) lst.Remove(vm1.DataGridViewRow);
} // I can see DataGridViewRows being matched with vm1.
} // Then, I expand IEnumerable 'vms' and check the value again. All
// the ViewModels lost their references to the matching DataGridViewRows.
// In every ViewModel.DataGridViewRow = null; WHY IS THIS HAPPENING??
//.... here is the background code of my model
public class CompanyViewModel : BaseViewModel, ICompanyViewModel {
public DataGridViewRow DataGridViewRow { get; set; }
public ICompany Company { get; set; }
public long ID {
get { return Company.ID; }
}
public string Name {
get { return Company.Name; }
set { Company.Name = value; }
}
}
public interface ICompanyViewModel : IViewModel {
DataGridViewRow DataGridViewRow { get; set; }
public ICompany Company { get; set; }
long ID { get; }
string Name { get; set; }
}
public interface IViewModel { }
public abstract class BaseViewModel : IViewModel { }