Get datagrid rows

44.3k views Asked by At

How can I get the list of rows in the DataGrid? Not the bound items, but the DataGridRows list.

I need to control the visibility of these rows and it's only possible to control it as a DataGridRow and not as a data object.

Thanks!

2

There are 2 answers

3
Rohit Vats On

You can get the row using ItemContainerGenerator. This should work -

for (int i = 0; i < dataGrid.Items.Count; i++)
{
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator
                                               .ContainerFromIndex(i);
}
5
Adi Lester On

I recommend defining a Style for DataGridRow that will have its Visibility bound to whether it should be displayed or not. Just iterating through the rows won't be enough, as I mentioned in @RV1987's answer.

<DataGrid>
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <Setter Property="Visibility" Value="{Binding ...}" />
        </Style>
    </DataGrid.Resources>
</DataGrid>

EDIT:

What you bind to depends on where you hold the information of whether or not you should display the row. For example, if each data object in your bound collection has a bool ShouldBeDisplayed property, you would have something like this:

<DataGrid>
    <DataGrid.Resources>
        <BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" />

        <Style TargetType="DataGridRow">
            <Setter Property="Visibility" Value="{Binding Path=ShouldBeDisplayed, Converter={StaticResource booleanToVisibilityConverter}}" />
        </Style>
    </DataGrid.Resources>
</DataGrid>