【问题标题】:How do I get the row of a selected cell in a DataGrid? [duplicate]如何获取 DataGrid 中选定单元格的行? [复制]
【发布时间】:2016-11-22 10:06:03
【问题描述】:

我正在开发一个 WPF 应用程序。我正在使用 DataGrid 控件来显示包含各种信息的字段列表。我在 Visual Studio Community 工具箱中找不到 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>

【问题讨论】:

标签: c# wpf datagrid


【解决方案1】:

您似乎正在使用事件和代码隐藏来实现您想要实现的目标。我建议你接受 MVVM 范式并实现数据绑定。您的代码将不再在事件和代码隐藏中(即不在视图中),而是在视图模型中。例如,要跟踪行更改,请将 SelectedItem 属性绑定到视图模型中的属性。然后响应行更改变得像将代码放入视图模型属性的设置器中一样微不足道。这个话题太长了,不能作为一个答案。祝你好运。

【讨论】:

  • #jp2g - 我很想学习 Binding,只是不确定它是如何工作的。你能指出一个适合我正在尝试的例子吗?我看到了这个例子: Customer customer = (Customer)myDataGrid.SelectedItem; 但我不知道如何访问当我在我的数据网格中选择一行时的代码。这来自stackoverflow.com/questions/3913580/…。谢谢
  • @Cass:看看这个example。正如您链接到的 SO 帖子中所述,您的视图模型需要具有读/写属性,例如“SelectedCustomer”。在该属性的设置器中,您编写代码以响应行更改。它需要在 setter 中,因为每当 DataGrid 的选定项发生更改时,WPF 绑定管道都会为您设置该属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 2012-07-16
  • 2013-04-04
  • 2012-04-24
相关资源
最近更新 更多