我使用此代码从数据网格中添加或删除列。每个列标题我都有鼠标进入和离开事件。对于新列,我还想在插入数据网格后添加相同的事件处理程序。
private void Columns_CollectionChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e)
{
if (e.Action == CollectionChangeAction.Add)
{
int columnPosition = (this.Columns.Count - 1);
DataGridTextColumn column = new DataGridTextColumn();
column.Header = (e.Element as DataColumn).ColumnName;
column.Binding = new Binding(string.Format("[{0}]", column.Header.ToString()));
this.Columns.Insert(columnPosition, column);
DataGridColumnHeader columnHeader = DataGridHelper.GetColumnHeader(this, columnPosition);
if (columnHeader != null)
{
columnHeader.MouseEnter += new MouseEventHandler(ColumnHeader_MouseEnter);
columnHeader.MouseLeave += new MouseEventHandler(ColumnHeader_MouseLeave);
}
SetAutomappingOnOff = false;
}
else if (e.Action == CollectionChangeAction.Remove)
{
DataColumn column = e.Element as DataColumn;
DataGridColumn toRemove = (from DataGridColumn dc in this.Columns
where dc.Header != null && dc.Header.ToString() == column.ColumnName
select dc).First();
this.Columns.Remove(toRemove);
SetAutomappingOnOff = false;
}
}
<编辑>
数据网格助手
public static class DataGridHelper
{
public static DataGridColumnHeader GetColumnHeader(DataGrid dataGrid, int index)
{
DataGridColumnHeadersPresenter presenter = FindVisualChild<DataGridColumnHeadersPresenter>(dataGrid);
if (presenter != null) {
return (DataGridColumnHeader)presenter.ItemContainerGenerator.ContainerFromIndex(index);
}
return null;
}
}
</编辑>
但是即使我可以看到该对象已创建并添加到数据网格中,columnHeader 始终返回 null。
请帮助我。
谢谢迪