我有一个网格需要在数据绑定后立即隐藏某些列。到目前为止,这是我的代码:
private IEnumerable<DataGridColumn> GetDataGridColumns(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var column = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridColumn;
if (null != column) yield return column;
}
}
private void LoadData()
{
GridMain.ItemsSource = (new VTAEEntities()).OrganizationInterfaces.ToList();
foreach (DataGridColumn Column in GetDataGridColumns(GridMain))
{
// Hiding columns
if (Column.Header as String != null) {
String tempHeader = Column.Header as String;
String[] unrequiredColumns = new String[] {
"Instances",
"Interfaces",
"Organizations",
"RegisteredCallerOnly"
};
if (unrequiredColumns.Contains(tempHeader)) {
Column.Visibility = System.Windows.Visibility.Hidden;
}
}
// Read-only columns
if (Column.Header as String != null)
{
String tempHeader = Column.Header as String;
String[] unrequiredColumns = new String[] {
"InstanceId",
"InterfaceId",
"OrganizationId"
};
if (unrequiredColumns.Contains(tempHeader))
{
Column.IsReadOnly = true;
}
}
}
}
所有不需要的列+我想只读的列都在那里。调试后,我意识到 GridMain.Columns 始终为 0 计数。如何遍历 ItemSource 中的列?