How to get DataGridColumnHeader from DataGridColumn?

后端 未结 2 1299
小鲜肉
小鲜肉 2020-12-07 02:02

My code is as follows:

 void mainDataContextObj_CutSelectedColumnEvent(string columnId)
    {
        IList columns = dg.Columns;

             


        
2条回答
  •  孤城傲影
    2020-12-07 02:22

    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 columnHeaders = GetVisualChildCollection(dataGrid);
        foreach (DataGridColumnHeader columnHeader in columnHeaders)
        {
            if (columnHeader.Column == column)
            {
                return columnHeader;
            }
        }
        return null;
    }
    
    public List GetVisualChildCollection(object parent) where T : Visual
    {
        List visualCollection = new List();
        GetVisualChildCollection(parent as DependencyObject, visualCollection);
        return visualCollection;
    }
    
    private void GetVisualChildCollection(DependencyObject parent, List 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);
            }
        }
    }
    

提交回复
热议问题