我用以下代碼頭痛。看起來非常直截了當,但我不明白爲什麼會出錯。我正確使用IEnumerable嗎?
這個想法很簡單,我只是循環添加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 { }
你是否嘗試註釋掉這一行:'if(vm1.DataGridViewRow!= null)lst.Remove(vm1.DataGridViewRow);'只是如果它工作的更好。 –