我在绑定到地址列表的 WinForm 应用程序中有一个数据网格。地址列表很长,所以我必须滚动选择我想要的地址。但是,在我滚动并找到我想要的地址并选择它之后,数据网格将选择第一次加载表单时位于网格上相同位置的地址。我想知道我做错了什么以及如何获得我想要的结果。
//
// bindingSource1
//
private System.Windows.Forms.BindingSource bindingSource1;
this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components);
this.bindingSource1.DataSource = typeof(ViewModels.ListAddressViewModel);
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToOrderColumns = true;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.HouseNumber,
this.Prefix,
this.StreetName,
this.StreetType,
this.StreetSuffix,
this.SecondaryType,
this.SecondaryNumber,
this.City,
this.State,
this.ZipCode});
this.dataGridView1.DataBindings.Add(new System.Windows.Forms.Binding("DataSource", this.bindingSource1, "AddressList", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location = new System.Drawing.Point(0, 50);
this.dataGridView1.MultiSelect = false;
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.ShowCellErrors = false;
this.dataGridView1.ShowCellToolTips = false;
this.dataGridView1.ShowEditingIcon = false;
this.dataGridView1.ShowRowErrors = false;
this.dataGridView1.Size = new System.Drawing.Size(1014, 421);
this.dataGridView1.TabIndex = 2;
this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
//Selection Change Handler
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
_vm.SelectedAddress = (Address)dataGridView1.SelectedRows[0].DataBoundItem;
}
}
//My View Model (_vm)
public class ListAddressViewModel
{
public IList<Address> AddressList { get; set; }
private IAddressRepository _repo;
public Address SelectedAddress {get;set;}
public ListAddressViewModel()
{
AddressList = new List<Address>();
}
public ListAddressViewModel(IAddressRepository AddrRepo)
:this()
{
_repo = AddrRepo
init();
}
private void init()
{
if(_repo != null)
{
AddressList = _repo.FindAll();
}
}
... etc..
}