wpf 获取数据网格行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12762310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:32:20  来源:igfitidea点击:

Get datagrid rows

wpfdatagridvisibilitydatagridrowheader

提问by user196625

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

如何获取 DataGrid 中的行列表?不是绑定项目,而是 DataGridRows列表。

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

我需要控制这些行的可见性,并且只能将其作为DataGridRow数据对象而不是数据对象进行控制。

Thanks!

谢谢!

回答by Rohit Vats

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

您可以使用ItemContainerGenerator获取该行。这应该有效 -

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

回答by Adi Lester

I recommend defining a Style for DataGridRowthat 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.

我建议为DataGridRow它定义一个样式,将其可见性绑定到是否应该显示。正如我在@RV1987 的回答中提到的那样,仅仅遍历行是不够的。

<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 ShouldBeDisplayedproperty, you would have something like this:

你绑定到什么取决于你保存是否应该显示行的信息。例如,如果绑定集合中的每个数据对象都有一个bool ShouldBeDisplayed属性,您将拥有如下内容:

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

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