0
votes

I'm looking for a simple way to retrieve all items in a specific column of a WPF DataGrid. I have both the DataGrid, DataGridColumn and DataGridColumnHeader as a reference, but I can't seem to find a logical way of getting the elements.

Using the Header property of the DataGridColumn is not an option as I'm using a custom Header object in some cases.

1
datagrid should be bind to come structured collection... like ObservableCollection<MyDataClass>... you should not use header, just get the instance of MyDataClass of specific row and use the getter of required propertyDivisadero
I'm preparing a generic control, not a specific case. And for that, I need not know which property is bound to the specific column. I'm looking for a generic solution that will return the values in a datagrid, in a specific column, after supplying it both the dg and the dgc.fonix232
and how do you tell the control which header should be shown for which property? I would start with that thenDivisadero
Have you tried to bind the content from the grid to a observable list in a one way bind ?FoldFence
I can't edit the DataContext, this must be done completely locally, in the UserControl I created for the whole thing (which is in turn inserted into the DataGriColumnHeader Template). The columns are defined manually within the XAML, but as I said, this is a control which MUST work in a generic way. If it was a single usage thing, I'd hardcode the whole shebang, but alas I can't.fonix232

1 Answers

0
votes

It is pretty straight forward to do that if you already have an instance of the DataGrid. Here is a simple extension method you can use to get an enumerable of all items in column of DataGrid.

namespace Extensions
{
    public static class DataGridExtension
    {
        public static IEnumerable<FrameworkElement> GetItemsInColumn(this DataGrid dg, int col)
        {
            if (dg.Columns.Count <= col)
                throw new IndexOutOfRangeException("Column " + col + " is out range, the datagrid only contains " + dg.Columns.Count + " columns.");
            foreach (object item in dg.Items)
            {
                yield return dg.Columns[col].GetCellContent(item);
            }
        }
    }
}

Then to call the method you can just do,

dg.GetItemsInColumn(colNumber);