单击鼠标获取网格单元格

我有一个WPF网格,分为3行和3列,我无法找到一种方法来获取鼠标点击网络的行和列号,哦,如果有可能它会更好我的程序,这部分将在代码而不是XAML,这是我的简单网格:

            

面对同样的问题,我提出了这个解决方案:

XAML:

  

注意: Grid必须有一个后台来提升鼠标按下事件,请参阅: 如果单击单元格中没有UIElemets,如何让Grid提升MouseDown事件?

代码隐藏:

 private void OnPreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { if(e.ClickCount == 2) // for double-click, remove this condition if only want single click { var point = Mouse.GetPosition(myGrid); int row = 0; int col = 0; double accumulatedHeight = 0.0; double accumulatedWidth = 0.0; // calc row mouse was over foreach (var rowDefinition in myGrid.RowDefinitions) { accumulatedHeight += rowDefinition.ActualHeight; if (accumulatedHeight >= point.Y) break; row++; } // calc col mouse was over foreach (var columnDefinition in myGrid.ColumnDefinitions) { accumulatedWidth += columnDefinition.ActualWidth; if (accumulatedWidth >= point.X) break; col++; } // row and col now correspond Grid's RowDefinition and ColumnDefinition mouse was // over when double clicked! } } 

在这里回答: 如何识别在WPF网格上点击了哪个单元格?

我以前从未使用过WPF Grid,但是以上面的链接为例我认为这样的事情应该这样做:

将其添加到Initialize方法:

 this.GridCtrl.MouseDown += new MouseButtonEventHandler(GridCtrl_MouseDown); 

并添加新方法来处理事件:

 private void GridCtrl_MouseDown(object sender, MouseButtonEventArgs e) { if (sender != null) { Grid _grid = sender as Grid; int _row = (int)_grid.GetValue(Grid.RowProperty); int _column = (int)_grid.GetValue(Grid.ColumnProperty); MessageBox.Show(string.Format("Grid clicked at column {0}, row {1}", _column, _row)); } } 

我使用这样的东西:

 private void DataGrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e) { // Check if the user double-clicked a grid row and not something else if (e.OriginalSource == null) return; var row = ItemsControl.ContainerFromElement((DataGrid)sender, e.OriginalSource as DependencyObject) as DataGridRow; // If so, go ahead and do my thing if (row != null) { var Item = (CLASS_YOU_USE_TO_BIND)DataGrid1.Items[row.GetIndex()]; //Here you can work with Item, it is now the object of class you used in //DataGrid.DataSource } } 

试试吧

 Grid.GetRow(NAME OF GRID) Grid.GetColumn(NAME OF GRID)