WPF数据网格获取所有选中的行(不使用WPF绑定)

本文关键字:WPF 绑定 数据网 数据 网格 获取 | 更新日期: 2023-09-27 18:20:12

如何使用C#代码隐藏获取WPF数据网格中所有选中的行?

我正在尝试使用这些代码进行批量删除,但我需要首先获得所有选中的行。

这是我的数据网格

<DataGrid x:Name="DiseaseSymptomsDataGrid" Grid.Row="1"
    SelectionMode="Extended"
    GridLinesVisibility="All" 
    CanUserSortColumns="False" 
    CanUserAddRows="False"                      
    HeadersVisibility="Column"
    AutoGenerateColumns="False"
    PreviewMouseLeftButtonUp="DiseaseSymptomsDataGrid_OnPreviewMouseLeftButtonUp"
            >
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="IdColumn" Binding="{Binding Id}" Header="Id" Visibility="Collapsed" IsReadOnly="True"/>
        <DataGridTextColumn x:Name="DiseaseIdColumn" Binding="{Binding DiseaseId}" Header="DiseaseId" Visibility="Collapsed" IsReadOnly="True"/>
        <DataGridTextColumn x:Name="DiseaseNameColumn" Binding="{Binding DiseaseName}" Header="Disease" Visibility="Collapsed" IsReadOnly="True"/>
        <DataGridTextColumn x:Name="SymptomIdColumn" Binding="{Binding SymptomId}" Header="SymptomId" Visibility="Collapsed" IsReadOnly="True"/>
        <DataGridTextColumn x:Name="SymptomNameColumn" Binding="{Binding SymptomName}" Header="Symptom" IsReadOnly="True"/>
        <DataGridTextColumn x:Name="DescriptionColumn" Binding="{Binding SymptomDescription}" Header="Description" Width="425" IsReadOnly="True"/>
        <DataGridCheckBoxColumn x:Name="StatusIdColumn" Header="Delete"  IsReadOnly="False"/>
    </DataGrid.Columns>
</DataGrid>

这是我在后面尝试的代码

public List<DiseaseSymptomParams> GetSelectedDiseaseSymptom()
{
    var entiParams = new DiseaseSymptomParams();
    var selectedDiseases = new List<DiseaseSymptomParams>();
    try
    {
        // this will only get the highlighted row, not ALL the checked rows
        foreach (DiseaseSymptom itemSelected in DiseaseSymptomsDataGrid.SelectedItems) 
        {
            entiParams.Id = DefaultValue.GetInt(itemSelected.Id);                   
            selectedDiseases.Add(entiParams);
        }
    }
    catch (Exception)
    {
    }
    return selectedDiseases;
}

WPF数据网格获取所有选中的行(不使用WPF绑定)

以下是您可以做的:

foreach (DiseaseSymptom item in DiseaseSymptomsDataGrid.ItemsSource)
{
    if (((CheckBox)StatusIdColumn.GetCellContent(item)).IsChecked == true)
    {
        selectedDiseases.Add(item);
    }
}

不符合MVVM,但务实。