Question How to iterate through WPF datagrid columns following mvvm pattern?

TB007

Member
Joined
Aug 13, 2022
Messages
24
Programming Experience
Beginner
I want to iterate through a datagrid header column and get its values to a variable, something like

C#:
            foreach (DataGridColumn column in gridView.Columns)
            {
                var cell = column.Header.ToString()
            }

How can I do this following mvvm?
 
But how do I apply it in my case ? I've tried

C#:
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Path=eName}" Width="260">
                        <DataGridTextColumn.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding DataContext.billHead1, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                            </DataTemplate>
                        </DataGridTextColumn.HeaderTemplate>
                    </DataGridTextColumn>
                    <DataGridTextColumn Binding="{Binding Path=eAddress}" Width="200">
                        <DataGridTextColumn.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding DataContext.billHead2, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                            </DataTemplate>
                        </DataGridTextColumn.HeaderTemplate>
                    </DataGridTextColumn>
                    <DataGridTextColumn Binding="{Binding Path=eAge}" Width="210">
                        <DataGridTextColumn.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding DataContext.billHead3, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
                            </DataTemplate>
                        </DataGridTextColumn.HeaderTemplate>
                    </DataGridTextColumn>
                </DataGrid.Columns>

But the headers are still not showing ...
 
The x:Type DataGrid should be the type of the container on which your view model is to to. So if you assigned the view model to the Window, use x:Type Window.
 

Latest posts

Back
Top Bottom