DataGrid 如何得到DataGridRow 和DataGridCell 对象

时间:2021-02-04 03:33:44
第一行为不可编辑
 DataGridRow row = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(0);
            if (row == null)
            {
                dataGrid1.UpdateLayout();
                row = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(0);
                 
         }
         row.IsEnabled = false;
        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T childContent = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                childContent = v as T;
                if (childContent == null)
                {
                    childContent = GetVisualChild<T>(v);
                }
                if (childContent != null)
                {
                    break;
                }
            }
            return childContent;
        }
  
  
//第二行第一列不可编辑
                 DataGridRow rowContainer = GetDataGridRow(dataGrid1, 1);
  
                if (rowContainer != null)
                {
                    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(1);
                    if (cell == null)
                    {
                        dataGrid1.ScrollIntoView(rowContainer, dataGrid1.Columns[0]);
                        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);
                        
                    }
  
                    cell.IsEnabled = false;
                }