/// <summary> /// Converts an <see cref="DataGridCell"/> to its row index. /// </summary> /// <param name="value">Value to be converted.</param> /// <param name="targetType">Type to convert to.</param> /// <param name="parameter">Optional conversion parameter.</param> /// <param name="culture">Globalization info.</param> /// <returns>The index of the cell. If none found, will return -1.</returns> public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) { DataGridCell item = value as DataGridCell; DataGridRow dataGridRow = item?.Ancestors().OfType <DataGridRow>().FirstOrDefault(); DataGrid dataGrid = dataGridRow?.Ancestors().OfType <DataGrid>().FirstOrDefault(); Int32 index = dataGrid?.ItemContainerGenerator.IndexFromContainer(dataGridRow) ?? -1; return(index.ToString()); }
private void OnDataGridPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (!(sender is VsDataGrid dataGrid)) { return; } FrameworkElement fe = GetFrameworkElement(e.OriginalSource); DataGridCell cell = fe?.Ancestors().OfType <DataGridCell>().FirstOrDefault(); if (cell == null || cell.IsEditing || cell.IsReadOnly || Keyboard.Modifiers != ModifierKeys.None) { return; } if (!cell.IsFocused) { cell.Focus(); } if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow) { if (!cell.IsSelected) { cell.IsSelected = true; } } else { DataGridRow row = cell.Ancestors().OfType <DataGridRow>().FirstOrDefault(); if (row == null || !row.IsSelected) { return; } row.IsSelected = true; } }