我使用此代码在datagrid中添加或删除列。每个列标题我有鼠标进入和离开事件。对于新列,我还希望在插入到datagrid后添加相同的事件处理程序。
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;
}
}
<编辑>
DataGridHelper
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;
}
}
&LT; /编辑&gt;
但是,即使我可以看到创建对象并将其添加到datagrid,columnHeader也始终返回null。
请帮助我。
由于 迪伊
答案 0 :(得分:0)
当列已添加到DataGrid时,它尚未添加到VisualTree中,因此FindVisualChild方法返回null。我没有为列添加单击处理程序的良好解决方案,但您可以将其添加到DataGrid并检查发件人以查看应用单击处理逻辑的位置。
答案 1 :(得分:0)
我建议在CollectionChanged
- s DataGrid
事件中注册Loaded
个事件。这样,您可以确保将DataGridColumnHeader
添加到可视树中。它看起来像这样:
myDataGrid.Loaded += (s,e) => {
myCollection.CollectionChanged += (se, ev) => {
//do work here
};
};