本文介绍了如何从 DataGridColumn 获取 DataGridColumnHeader?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码如下:
void mainDataContextObj_CutSelectedColumnEvent(string columnId)
{
IList<DataGridColumn> columns = dg.Columns;
for(int i=2; i<dg.Columns.Count; i++)
{
DataGridColumnHeader headerObj = dg.Columns[i].Header as DataGridColumnHeader;
//This always returns headerObj as null!!!
}
}
我需要列中的 DataGridColumnHeader
.我哪里出错了?
I need DataGridColumnHeader
from the column. Where am I going wrong?
推荐答案
DataGridColumn 的 Header 对象实际上是该列的可见标题,无论您将其设置为什么.DataGridColumn 不是可视化树的一部分,因此没有直接的方法来访问它的 DataGridColumnHeader(我们甚至不能确定它是否存在).但是你可以做这样的事情来尝试访问它
The Header object of the DataGridColumn is actually the visible header of that column, whatever you set it to be. DataGridColumn is not part of the Visual Tree so there is not direct way to access the DataGridColumnHeader for it (we can't even be sure it exists yet). But you can do something like this to try and access it
DataGridColumnHeader headerObj = GetColumnHeaderFromColumn(column);
private DataGridColumnHeader GetColumnHeaderFromColumn(DataGridColumn column)
{
// dataGrid is the name of your DataGrid. In this case Name="dataGrid"
List<DataGridColumnHeader> columnHeaders = GetVisualChildCollection<DataGridColumnHeader>(dataGrid);
foreach (DataGridColumnHeader columnHeader in columnHeaders)
{
if (columnHeader.Column == column)
{
return columnHeader;
}
}
return null;
}
public List<T> GetVisualChildCollection<T>(object parent) where T : Visual
{
List<T> visualCollection = new List<T>();
GetVisualChildCollection(parent as DependencyObject, visualCollection);
return visualCollection;
}
private void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Visual
{
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child is T)
{
visualCollection.Add(child as T);
}
else if (child != null)
{
GetVisualChildCollection(child, visualCollection);
}
}
}
这篇关于如何从 DataGridColumn 获取 DataGridColumnHeader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!