WPF-如何在数据网格中获取选定的行索引?

WPF- How to get selected row index in datagrid?

我在数据网格中有文本框。数据正在从数据库中获取。假设我有 10 行具有这些文本框值。一旦我点击这一行,就可以获得这个选定的行索引。我的目标是,如果文本框值发生变化,我需要检测它是哪一行(哪个值)并根据该值进行一些计算,然后需要显示同一行的另一个字段。所以我能够知道哪一行被击中了。 `我正在使用带有以下声明的数据网格:

    <dg:DataGrid Name="dgBudgetAllocation" CanUserDeleteRows="False" CanUserAddRows="False" CanUserSortColumns="True"
                        IsSynchronizedWithCurrentItem="True" MaxHeight="400" RowHeight="70" SelectionUnit="Cell" SelectedValue="" SelectionMode="Single"
                 AutoGenerateColumns="False" GridLinesVisibility="None"  HeadersVisibility="Column"  PreviewMouseDown="DgBudgetAllocation_OnPreviewMouseDown" SelectedCellsChanged="DgBudgetAllocation_OnSelectedCellsChanged" MouseDown="DgBudgetAllocation_OnMouseDown" PreviewMouseUp="DgBudgetAllocation_OnPreviewMouseUp"  PreviewKeyDown="DgBudgetAllocation_OnPreviewKeyDown" HorizontalAlignment="Left">


                       <dg:DataGridTemplateColumn Header="Budget Type" SortMemberPath="BUDGETYPE"
                                       MinWidth="50" HeaderStyle="{DynamicResource dgHeaderLeftJust}" CellStyle="{DynamicResource dgColumnRightJust}">
                <dg:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding BUDGETYPE}" HorizontalAlignment="left" VerticalAlignment="Top" Margin="0,0,3,0" />
                    </DataTemplate>
                </dg:DataGridTemplateColumn.CellTemplate>

            </dg:DataGridTemplateColumn>

我根据不同人的建议尝试了以下代码片段。对于所有我得到的选定索引是-1。

DataRowView drv = (DataRowView)dgBudgetAllocation.SelectedItem;
                object item = dgBudgetAllocation.SelectedItem;
                string ID = (dgBudgetAllocation.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
                DataGrid row1 = (DataGrid)dgBudgetAllocation.SelectedItems[1];
                var row = dgBudgetAllocation.SelectedItems[0]; 

没有任何效果。 请建议我如何进一步进行。

c订阅选择更改事件 (SelectionChanged="ItemsView_OnSelectionChanged") 并使用处理程序获取您需要的所有内容。您可以在行为(和 MVVM)中执行此操作,或者只是将处理程序放在您的代码后面。

处理程序代码示例

 private void ItemsView_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var dg = sender as DataGrid;
        if (dg == null) return;
        var index = dg.SelectedIndex;
        //here we get the actual row at selected index
        DataGridRow row = dg.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;

        //here we get the actual data item behind the selected row
        var item = dg.ItemContainerGenerator.ItemFromContainer(row);

    }

如果您需要更多解释,请告诉我。 问候。