简体   繁体   English

WPF DataGrid:如何确定当前行索引?

[英]WPF DataGrid: How to Determine the Current Row Index?

I am trying to implement a very simple spreadsheet functionality based on a DataGrid.我正在尝试基于 DataGrid 实现一个非常简单的电子表格功能。

  1. The user clicks on a cell用户点击一个单元格

  2. The user types a value and presses return用户输入一个值并按下回车键

  3. The current row is scanned and any cell formula that depends on the clicked cell is updated.扫描当前行并更新依赖于单击的单元格的任何单元格公式。

This seems to be the best event handler for my requirements:这似乎是满足我要求的最佳事件处理程序:

private void my_dataGrid_CurrentCellChanged(object sender, EventArgs e)

Question: How do I detect the row index of the current row?问题:如何检测当前行的行索引?

Try this (assuming the name of your grid is "my_dataGrid"):试试这个(假设你的网格名称是“my_dataGrid”):

var currentRowIndex = my_dataGrid.Items.IndexOf(my_dataGrid.CurrentItem);

Normally, you'd be able to use my_dataGrid.SelectedIndex , but it seems that with the CurrentCellChanged event, the value of SelectedIndex always displays the previously selected index.通常,您可以使用my_dataGrid.SelectedIndex ,但似乎对于CurrentCellChanged事件, SelectedIndex 的值始终显示先前选择的索引。 This particular event seems to fire before the value of SelectedIndex actually changes.此特定事件似乎在 SelectedIndex 的值实际更改之前触发。

The accepted solution will work until you have no reference-duplicates in the ItemsSource , otherwise you will get index of the object's first occurrence.接受的解决方案将一直有效,直到您在ItemsSource没有引用重复,否则您将获得对象第一次出现的索引。

The solution from BRAHIM Kamel will work until you have a selection, otherwise(if you click twice and deselect a cell/row) you will not have a SelectedIndex . BRAHIM Kamel解决方案将一直有效,直到您有选择为止,否则(如果您单击两次并取消选择单元格/行),您将没有SelectedIndex

With YourDataGrid.ItemContainerGenerator.ContainerFromItem( _dataItemFromCurentCell ) as DataGridRow you will get by duplicates always the last occurrence of data item.使用YourDataGrid.ItemContainerGenerator.ContainerFromItem( _dataItemFromCurentCell ) as DataGridRow您将始终通过重复项获得最后一次出现的数据项。

I would handle DataGrid.PreviewMouseLeftButtonDown event and search in handler the visual tree up to a DatagridRow , which has DatagridRow.GetIndex() method.我会处理DataGrid.PreviewMouseLeftButtonDown事件并在处理程序中搜索可视化树直到DatagridRow ,它具有DatagridRow.GetIndex()方法。 So you will get always the right row index .因此,您将始终获得正确的行索引

<DataGrid ... PreviewMouseLeftButtonDown="Previe_Mouse_LBtnDown" >
    ...
</DataGrid>

private void Previe_Mouse_LBtnDown(object sender, MouseButtonEventArgs e)
{
    DataGridRow dgr = null;
    var visParent = VisualTreeHelper.GetParent(e.OriginalSource as FrameworkElement);
    while (dgr == null && visParent != null)
    {
        dgr = visParent as DataGridRow;
        visParent = VisualTreeHelper.GetParent(visParent);
    }
    if (dgr == null) { return; }

    var rowIdx=dgr.GetIndex();
}

Hi you can do something like this to do your spreadsheed嗨,你可以做这样的事情来做你的电子表格

 //not recomended  as it always  return the previous index of the selected row 
 void dg1_CurrentCellChanged(object sender, EventArgs e)
    {

       int rowIndex = dg1.SelectedIndex;   
     }

but if you want a more elaborated example this is how you can do it但如果你想要一个更详细的例子,这就是你可以做到的

namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    ObservableCollection<Tuple<string,string>> observableCollection = new ObservableCollection<Tuple<string,string>>();  
    public MainWindow()
    {
        InitializeComponent();            
        for (int i = 0; i < 100; i++)
        {
            observableCollection.Add( Tuple.Create("item " + i.ToString(),"=sum (c5+c4)"));
        }

        dg1.ItemsSource = observableCollection; 

        dg1.CurrentCellChanged += dg1_CurrentCellChanged;

    }

    void dg1_CurrentCellChanged(object sender, EventArgs e)
    {
        //int rowIndex = dg1.SelectedIndex;   
        Tuple<string, string> tuple = dg1.CurrentItem as Tuple<string, string>; 
        //here as you have your datacontext you can loop through and calculate what you want 

    }
}
}

Hope this help希望这有帮助

1.When click on the Cell inside the Datagrid, Get the CurrentCell info 1.点击Datagrid内的Cell,获取CurrentCell信息

2.From the DatagridCellInfo, we can find Column and Row index of particular cell 2.从DatagridCellInfo中,我们可以找到特定单元格的Column和Row索引

private void CellClick(object sender,RoutedEventArgs e)
    {
     DataGridCellInfo cell=DataGrid.CurrentCell;
     int columnindex=cell.Column.DisplayIndex;
     int rowIndex=DataGrid.Items.IndexOf(cell.Item);
    }
GRD.Items.Count;
DataGridRow row = (DataGridRow) GRD.ItemContainerGenerator.ContainerFromIndex(i);     
DataGridCell TXTGROUPID = GRD.Columns[2].GetCellContent(row).Parent as DataGridCell;               
string str = ((TextBlock) TXTGROUPID.Content).Text;
MessageBox.Show(str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM