C# 如何获取数据网格中选定单元格的行?

C# 如何获取数据网格中选定单元格的行?,c#,wpf,datagrid,C#,Wpf,Datagrid,我有一个WPF应用程序,我正在工作。我使用DataGrid控件显示包含各种信息的字段列表。在Visual Studio社区工具箱中找不到DatGridView控件。我的大多数谷歌搜索只返回DataGridView的信息,非常令人沮丧。如果我能找到,我会使用DataGridView,但我离题了。我希望能够在用户选择单元格时捕获当前行,以便从相邻单元格中获取值。我不知道该怎么做。以下是我创建DataGrid的方法: private void DisplayFieldLengths(string s

我有一个WPF应用程序,我正在工作。我使用DataGrid控件显示包含各种信息的字段列表。在Visual Studio社区工具箱中找不到DatGridView控件。我的大多数谷歌搜索只返回DataGridView的信息,非常令人沮丧。如果我能找到,我会使用DataGridView,但我离题了。我希望能够在用户选择单元格时捕获当前行,以便从相邻单元格中获取值。我不知道该怎么做。以下是我创建DataGrid的方法:

 private void DisplayFieldLengths(string strFLFileName, Int32 intTotalRowSize, int[] intFieldLengths)
    {
        int intDisplayCnt, colCnt = 0;
        string strData = "";


        lblFLInfo.Content = "File: " + strFLFileName;
        DataTable dt = new DataTable();
        dt.Columns.Add("Field", typeof(string));
        dt.Columns.Add("Size", typeof(string));
        dt.Columns.Add(" New Size", typeof(string));
        dt.Columns[0].ReadOnly = true;
        dt.Columns[1].ReadOnly = true;


        for (intDisplayCnt = 0; intDisplayCnt < intFieldLengths.Length; intDisplayCnt++)
        {
            strData = "Field" + (intDisplayCnt + 1) + "|" + intFieldLengths[intDisplayCnt].ToString() + "|1";
            dt.Rows.Add(strData.Split('|'));
        }

        dtGrid.ItemsSource = dt.DefaultView;
        lblRowSize.Content = "Total row length: " + intTotalRowSize;

    }
下面是DataGrid的xaml

<DataGrid IsReadOnly="False" Name="dtGrid" Loaded="GridLoaded" CurrentCellChanged="NewFieldSizeChanged" HorizontalAlignment="Left" VerticalAlignment="Top" Height="365" Margin="48,53,0,0" Width="272" BorderThickness="1" BorderBrush="Black">
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridCell}">
                <Style.Triggers>
                    <Trigger Property="DataGridCell.IsSelected" Value="True">
                        <Setter Property="Background" Value="#FF9DF3D6" />
                        <Setter Property="Foreground" Value="#000000" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGrid.Resources>
    </DataGrid>

看起来您正在使用事件和代码隐藏来实现您想要实现的目标。我建议您采用MVVM范式并实现数据绑定。您的代码将不再位于事件和代码隐藏中,即不在视图中,而是在视图模型中。例如,要跟踪行更改,请将SelectedItem属性绑定到视图模型中的属性。然后,响应行更改就变得和将代码放入视图模型属性的setter一样简单。这个题目太长了,不能作为一般的答案。祝你好运。

这里已经给出了答案:jp2g-我很想学习绑定,只是不知道它是如何工作的。你能给我举一个适合我的例子吗?我看到了这个示例:Customer=CustomermyDataGrid.SelectedItem;但当我在datagrid中选择一行时,我不知道如何访问代码。这是从哪里来的。感谢you@Cass:看看这个。正如您链接到的SO帖子中所解释的,您的视图模型需要具有读/写属性,例如“SelectedCustomer”。在该属性的setter中,您编写代码以响应行更改。它需要在setter中,因为每当DataGrid的选定项发生更改时,WPF绑定管道将为您设置该属性。