我正在使用 DataGridView启用了MultiSelect的(Windows窗体),它位于用户控件中。我想通过调用实现以下代码的公共方法来更新用户控件外部的所有选定行:

foreach(DataGridViewRow dr in dataGridView.SelectedRows)
{
    MyBusiness business = (MyBusiness)dr.DataBoundItem;
    business.Rating = 5;
}

不幸的是,当选择多行时,只会立即刷新一个DataGridViewRow,即上次选择的那个。更改基础对象,并触发NotifyPropertyChange事件。此外,当我在更新后更改选择时,我看到所有行都完全按照我希望的方式更新。

第二件事,非常奇怪:当我在Rating - 的属性Setter中设置一个断点,其中NotifyPropertyChange被触发并在继续执行代码之前等待几秒钟,一切正常(所有行都会立即更新)。如果我不等待,但每次断点通过时都很快按F5,我会得到上述效果。

我的业务对象看起来像这样(当然会明显缩短):

public class MyBusiness : INotifyPropertyChanged
{
    private int _rating;
    public int Rating
    {
        get { return _rating; }
        set
        {
            if(_rating != value)
            {
                _rating = value;
                NotifyPropertyChanged("Rating");
            }
        }
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

是否有人已经注意到这种行为,甚至知道解决方案(或解决方法)?

有帮助吗?

解决方案

如果您的DGV绑定到常规列表,它只会订阅当前所选行的PropertyChanged事件。请尝试使用BindingList,或者为每个更改的项调用BindingSource.ResetItem(n)。

MSDN提供了一个示例,它使用了BindingList以及(无意义地)调用ResetItem。玩他们的示例,您可以看到删除对ResetItem的调用,或用regualr List <!> lt; <!> gt替换BindingList;将按预期运作。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top