关于SOF的类似问题似乎没有明确的答案。
我有一个DataGridView
绑定到一个BindingList<T>
对象(这是自定义对象的列表;也继承INotifyPropertyChanged
)。每个自定义对象都有一个独特的计时器。当这些计时器超过某个值(例如 10 秒)时,我想将单元格的前景色更改为红色。
我正在使用CellValueChanged
事件,但这个事件似乎永远不会触发,尽管我可以看到计时器在变化DataGridView
。我应该寻找其他活动吗?下面是我的CellValueChanged
处理程序。
private void checkTimerThreshold(object sender, DataGridViewCellEventArgs e)
{
TimeSpan ts = new TimeSpan(0,0,10);
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
if (orderObjectMapping[dataGridView1["OrderID", e.RowIndex].Value.ToString()].getElapsedStatusTime().CompareTo(ts) > 0)
{
DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
cellStyle.ForeColor = Color.Red;
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = cellStyle;
}
}
据我所知,当 DataSource 以编程方式更改时,无法使 DataGridView 引发事件 - 这是设计使然。
我能想到的满足您的要求的最佳方法是将 BindingSource 引入混合中 - 绑定源在其 DataSource 更改时会引发事件。
像这样的东西是有效的(显然你需要根据你的需要对其进行微调):
bindingSource1.DataSource = tbData;
dataGridView1.DataSource = bindingSource1;
bindingSource1.ListChanged += new ListChangedEventHandler(bindingSource1_ListChanged);
public void bindingSource1_ListChanged(object sender, ListChangedEventArgs e)
{
DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
cellStyle.ForeColor = Color.Red;
dataGridView1.Rows[e.NewIndex].Cells[e.PropertyDescriptor.Name].Style = cellStyle;
}
另一种选择是通过直接订阅数据来实现此目的 - 如果它是 BindingList,它将使用自己的 ListChanged 事件传播 NotifyPropertyChanged 事件。在更多 MVVM 场景中,这可能会更干净,但在 WinForms 中,BindingSource 可能是最好的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)