2023年6月13日

Datagrid Make the only row editable whose edit button is clicked , and other rows should not be editable

作者 dikangqie

Datagrid Make the only row editable whose edit button is clicked , and other rows should not be editable (microsoft.com)

private void OnEditClick(object sender, MouseEventArgs e) {
      Button button = sender as Button;
      DataGridRow row = FindVisualParent<DataGridRow>(button);
      DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(row);
      var viewModel = this.DataContext as YourViewModelType;
      for (int i = 0; i < dGrid.Columns.Count; ++i) {
        DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(i) as DataGridCell;
        if (cell != null)
          cell.IsEditing = viewModel.IsPausePlayModeEnabled && CanEndTaskVar; //or whatever your logic is...
      }
    }

private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
        {
            var parent = VisualTreeHelper.GetParent(dependencyObject);
 
            if (parent == null) return null;
 
            var parentT = parent as T;
            return parentT ?? FindParent<T>(parent);
        }