Search code examples
wpfxamlmvvmwpfdatagrid

How to get field that datagrid column is bound to?


In my xaml I have modified each column header to include a button. For the command parameter I would like to use the column's data field name, instead of the header content. E.g. Instead of "Job Title" which is what the header content is, I want "JOB_TITLE".

For header content I would use:

<Button Command="{Binding DataContext.OpenFilterCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{TemplateBinding Content}">

How do I get the actual field name?


Solution

  • If i assume it right you want binding property name to which column is binded to pass as command parameter to OpenFilterCommand.

    Suppose columns are like this for your DataGrid:

            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding NAME}"/>
                <DataGridTextColumn Binding="{Binding JOB_TITLE}" />
            </DataGrid.Columns>
    

    and want to pass property name JOB_TITLE as command parameter. This can be achieve like this:

    <Button Command="{Binding DataContext.OpenFilterCommand,
                         RelativeSource={RelativeSource AncestorType=UserControl}}"
            CommandParameter="{Binding Column.Binding.Path.Path,
                         RelativeSource={RelativeSource Mode=TemplatedParent}}"/>
    

    EXPLANATION

    TemplatedParent (DataGridColumnHeader) --> Column (DataGridTextColumn) --> Binding (BindingBase) --> Path (PropertyPath) --> Path (Actual PropertyName)