我的代码如下:

 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。我要去哪里错了?

最佳答案

无论您将其设置为什么,DataGridColumn的Header对象实际上是该列的可见标题。 DataGridColumn不是可视树的一部分,因此没有直接访问它的DataGridColumnHeader的方法(我们甚至不能确定它是否存在)。但是您可以执行以下操作尝试并访问它

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);
        }
    }
}

关于wpf - 如何从DataGridColumn获取DataGridColumnHeader?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4030764/

10-12 07:22