小编San*_*osh的帖子

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

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

    <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>
Run Code Online (Sandbox Code Playgroud)

我根据不同的人的建议尝试了以下代码段。对于所有我得到的选定索引是-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]; 
Run Code Online (Sandbox Code Playgroud)

没有任何工作。请建议我如何进一步进行。

c# wpf datagrid wpfdatagrid

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1

datagrid ×1

wpf ×1

wpfdatagrid ×1