Modificar la altura de las líneas de un DataGrid

1901 vistas

Tendremos que usar las funcionalidades de System.Windows.Reflection. Para el ejemplo, implementaremos nuestra propia clase MiDataGrid derivada de DataGrid.



csharp
  1. using System;
  2. using System.Reflection;
  3. using System.Windows.Forms;
  4.  
  5. public class MiDataGrid : DataGrid
  6. {
  7.   public MoDataGrid(): base()
  8.   {}
  9.  
  10.   //...
  11.  
  12.   // método público que permite la modificación de la altura de la línea indicada
  13.   public void setRowHeight(int rowindex, int rowheight)
  14.   {
  15.     // recuperamos la tabla de líneas
  16.     Object[] rows = GetRows();
  17.  
  18.     // decidimos de modificar todas las líneas con un valor negativo
  19.     if(rowindex < 0)
  20.     {
  21.       foreach(object row in rows)
  22.       { setHeight(row,rowheight);}
  23.     }
  24.     else
  25.     { setHeight(rows[rowindex],rowheight);}   
  26.   }
  27.  
  28.   // obtenemos todas las líneas por reflection
  29.   private object[] GetRows()
  30.   {
  31.     BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic;
  32.     Type t = this.GetType().BaseType;
  33.     MethodInfo mi = t.GetMethod("get_DataGridRows",bf);
  34.     return ((Object[])(mi.Invoke(this,null)));
  35.   }
  36.  
  37.   // modificar la altura de la línea por reflection
  38.   private void setHeight(object row, int rowheight)
  39.   {
  40.     row.GetType().GetProperty("Height").SetValue(row, rowheight, null);
  41.   }
  42. }