SoloCodigo

CLR: .Net / Mono / Boo / Otros CLR => C# => Mensaje iniciado por: Jeysscarr en Sábado 15 de Mayo de 2010, 19:25

Título: Código Barra de Información estilo Windows 7
Publicado por: Jeysscarr en Sábado 15 de Mayo de 2010, 19:25
Hola a todos, muy buenas tardes

Actualmente he creado un prototipo de barra de información basada en la forma de la barra de descripción que se usa en Windows 7, ese panel que muestra la informaciíon de los archivos o carpetas que seleccionamos.

La he creado con la finalidad de mostrar datos caracteristicos de elementos que el usuario seleccione en mis aplicaciones y datos estadisticos para varios elementos... he agregado la funcionalidad de adaptarse al tamaño de los elementos informativos que se le agreguen, es decir, si en modo de ejecución se le pasan parametros para nuevos valores, este cambia la posición de los controles para ahorrar espacio o mostrar la información completa.

Hasta el momento he logrado mi objetivo, y me gusta mucho como se ve en funcionamiento ya que para mostrar las propiedades de un objeto no necesito crear controles especificos para cada uno.

En Fin.. lo que quisiera es que opinaran acerca de que debería agregar para que cuando el usuario Agrande o haga mas pequeño el control, los Labels que ya estan agregados se adapten al nuevo tamaño como en windows 7, en donde uno agranda la barra y los elementos que estaban en una columna se pasan para la primera para no dejar espacios vacios, etc.

A continuación mi código de la clase y un ejemplo de como lo uso

1. Clase LABEL_ (Extendida de Label)
Código: C#
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows.Forms;
  6.  
  7. namespace ControlBarraDescripcion
  8. {
  9.     public class Label_:Label
  10.     {
  11.         int col=0;
  12.         public int Columna
  13.         {
  14.             get { return col; }
  15.             set { col = value; }
  16.         }
  17.  
  18.         bool ed = false;
  19.         public bool esDescripcion
  20.         {
  21.             get { return ed; }
  22.             set { ed = value; }
  23.         }
  24.  
  25.         string desc = null;
  26.         public string Descripcion
  27.         {
  28.             get { return desc; }
  29.             set { desc = value; }
  30.         }
  31.  
  32.         public bool CorrespondeDescripcion(string descrip)
  33.         {
  34.             if (Descripcion == null)
  35.             {
  36.                 return false;
  37.             }
  38.             else
  39.             {
  40.                 if (Descripcion == descrip)
  41.                 {
  42.                     return true;
  43.                 }
  44.                 else
  45.                 {
  46.                     return false;
  47.                 }
  48.             }
  49.         }
  50.     }
  51. }
  52.  
  53.  

2. Control Barra Información
Código: C#
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Drawing;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9.  
  10. namespace ControlBarraDescripcion
  11. {
  12.     public partial class BarraInformacion : UserControl
  13.     {
  14.  
  15.         public class InfoColumna
  16.         {
  17.             public int Index = 0;
  18.             public Label_ LabelDescripcionMasAncho = null;
  19.             public Label_ LabelValorMasAncho = null;
  20.  
  21.             public InfoColumna(Label_ Ldesc, Label_ LValor)
  22.             {
  23.                 LabelDescripcionMasAncho = Ldesc;
  24.                 LabelValorMasAncho = LValor;
  25.             }
  26.        
  27.         }
  28.  
  29.         public List<InfoColumna> ListaColumnas = new List<InfoColumna>();
  30.  
  31.         public BarraInformacion()
  32.         {
  33.             InitializeComponent();
  34.         }
  35.  
  36.  
  37.         public int posY = 0;
  38.         public int posX = 0;
  39.         public int cols = 0;
  40.         public int mayorAncho = 0;
  41.         public Label_ LabelDescripcionMasAncho = null;
  42.  
  43.         public Label_ ultimoLabel = null;
  44.         public int cont = 0;
  45.         public bool NuevaColumnaVacia = false;
  46.  
  47.         public Color ColorDescripcion=Color.DimGray;
  48.         public Color ColorValor = Color.Black;
  49.  
  50.         ImageList iml=null;
  51.         public ImageList Imagenes
  52.         {
  53.             get { return iml; }
  54.             set { iml = value; }
  55.         }
  56.  
  57.         public void Iniciar(Color ColorDescripcion, Color ColorValor, string titulo, int imageindex)
  58.         {
  59.             panel1.Controls.Clear();
  60.  
  61.             this.ColorDescripcion = ColorDescripcion;
  62.             this.ColorValor = ColorValor;
  63.            
  64.             posX = 0; posY = 0; cols = 0; mayorAncho = 0; ListaColumnas.Clear();
  65.  
  66.             LbTITULO.Text = titulo;
  67.             Pct.Image = null;
  68.             ultimoLabel = null;
  69.  
  70.             NuevaColumnaVacia = false;
  71.             LabelDescripcionMasAncho = null;
  72.  
  73.             cont = 0;
  74.  
  75.             if (Imagenes != null)
  76.             {
  77.                 if (imageindex != -1)
  78.                 {
  79.                    
  80.                     Pct.Image = Imagenes.Images[imageindex];
  81.                 }
  82.                 else
  83.                     Pct.Image = null;
  84.                
  85.             }
  86.  
  87.            
  88.         }
  89.  
  90.         public void AgregarDescripcion(string descripcion, string valor,bool CrearNuevosControles)
  91.         {
  92.             if (CrearNuevosControles)
  93.             {
  94.                 if (ultimoLabel == null)
  95.                 {
  96.                     //es el primero
  97.                     Label_ Ldescripcion = new Label_();
  98.                     panel1.Controls.Add(Ldescripcion);
  99.                     Ldescripcion.Tag = cont;
  100.                     cont++;
  101.  
  102.                     Ldescripcion.AutoSize = true;
  103.                     //Ldescripcion.BorderStyle = BorderStyle.FixedSingle;
  104.                     Ldescripcion.Text = descripcion + ":";
  105.                     Ldescripcion.esDescripcion = true;
  106.                     Ldescripcion.Location = new Point(posX, posY);
  107.                     Ldescripcion.Visible = true;
  108.                     Ldescripcion.Columna = cols;
  109.                     Ldescripcion.ForeColor = ColorDescripcion;
  110.                     posY = Ldescripcion.Bounds.Bottom + 4;
  111.  
  112.  
  113.                     ultimoLabel = Ldescripcion;
  114.  
  115.                     //Label_ del valor
  116.                     Label_ Lvalor = new Label_();
  117.                     panel1.Controls.Add(Lvalor);
  118.                     Lvalor.Tag = cont;
  119.                     Lvalor.Descripcion = descripcion;
  120.                     cont++;
  121.  
  122.                     Lvalor.AutoSize = true;
  123.                     //Lvalor.BorderStyle = BorderStyle.FixedSingle;
  124.                     Lvalor.Text = valor;
  125.                     Lvalor.Location = new Point(Ldescripcion.Right, Ldescripcion.Bounds.Y);
  126.                     Lvalor.Visible = true;
  127.                     Lvalor.Columna = cols;
  128.                     Lvalor.ForeColor = ColorValor;
  129.  
  130.                     ListaColumnas.Add(new InfoColumna(Ldescripcion, Lvalor));
  131.  
  132.                 }
  133.                 else
  134.                 {
  135.                     Label_ Ldescripcion = new Label_();
  136.                     panel1.Controls.Add(Ldescripcion);
  137.                     Ldescripcion.Tag = cont;
  138.                     cont++;
  139.  
  140.                     Ldescripcion.AutoSize = true;
  141.                     //Ldescripcion.BorderStyle = BorderStyle.FixedSingle;
  142.                     Ldescripcion.Text = descripcion + ":";
  143.                     Ldescripcion.esDescripcion = true;
  144.                     Ldescripcion.Location = new Point(posX, posY);
  145.                     Ldescripcion.Visible = true;
  146.                     Ldescripcion.Columna = cols;
  147.                     Ldescripcion.ForeColor = ColorDescripcion;
  148.                     posY = Ldescripcion.Bounds.Bottom + 4;
  149.                     ultimoLabel = Ldescripcion;
  150.  
  151.                     //Label_ del valor
  152.                     Label_ Lvalor = new Label_();
  153.                     panel1.Controls.Add(Lvalor);
  154.                     Lvalor.Tag = cont;
  155.                     Lvalor.Descripcion = descripcion;
  156.                     cont++;
  157.  
  158.                     Lvalor.AutoSize = true;
  159.                     //Lvalor.BorderStyle = BorderStyle.FixedSingle;
  160.                     Lvalor.Text = valor;
  161.                     Lvalor.Location = new Point(Ldescripcion.Right, Ldescripcion.Bounds.Y);
  162.                     Lvalor.Visible = true;
  163.                     Lvalor.Columna = cols;
  164.                     Lvalor.ForeColor = ColorValor;
  165.  
  166.                     if (NuevaColumnaVacia == true)
  167.                     {
  168.                         ListaColumnas.Add(new InfoColumna(Ldescripcion, Lvalor));
  169.  
  170.                         NuevaColumnaVacia = false;
  171.                     }
  172.  
  173.                     if (Lvalor.Width > ListaColumnas[cols].LabelValorMasAncho.Width)
  174.                     {
  175.                         ListaColumnas[cols].LabelValorMasAncho = Lvalor;
  176.                     }
  177.  
  178.                     //determinar si el ancho de este Label_ es mayor que el de los demás
  179.                     if (Ldescripcion.Size.Width > ListaColumnas[cols].LabelDescripcionMasAncho.Width)
  180.                     {
  181.                         ListaColumnas[cols].LabelDescripcionMasAncho = Ldescripcion;
  182.  
  183.                         //alinear los Labels de arriba a la derecha de este control
  184.                         foreach (Label_ lb in panel1.Controls)
  185.                         {
  186.                             if (lb.esDescripcion == true && (int)lb.Columna == cols)
  187.                             {
  188.                                 lb.Left = ListaColumnas[cols].LabelDescripcionMasAncho.Right - lb.Width;
  189.                             }
  190.                             else if (lb.esDescripcion == false && (int)lb.Columna == cols)
  191.                             {
  192.                                 lb.Left = ListaColumnas[cols].LabelDescripcionMasAncho.Right;
  193.                             }
  194.                         }
  195.                     }
  196.                     else
  197.                     {
  198.                         Ldescripcion.Left = ListaColumnas[cols].LabelDescripcionMasAncho.Right - Ldescripcion.Width;
  199.                         Lvalor.Left = Ldescripcion.Right + 2;
  200.                     }
  201.  
  202.                     if (panel1.Height - ultimoLabel.Bottom < 16)
  203.                     {
  204.                         //crear una nueva columna
  205.                         posX = ListaColumnas[cols].LabelValorMasAncho.Right + 2;
  206.                         posY = 0;
  207.                         NuevaColumnaVacia = true;
  208.                         cols++;
  209.  
  210.                     }
  211.                 }
  212.             }
  213.             else
  214.             {
  215.                 foreach (Label_ Lb in panel1.Controls)
  216.                 {
  217.                     if (Lb.CorrespondeDescripcion(descripcion))
  218.                     {
  219.                         Lb.Text = valor;
  220.                         break;
  221.                     }
  222.                 }
  223.             }
  224.            
  225.         }
  226.  
  227.         public void ReordenarItems()
  228.         {
  229.             if (cont > 0)
  230.             {
  231.                
  232.                 List<Label_> Lista = new List<Label_>();
  233.  
  234.                 foreach(Label_ Lb in panel1.Controls)
  235.                 {
  236.                     Lista.Add(Lb);    
  237.                 }
  238.  
  239.                 int mayorAnchoD = 0, mayorAnchoV = 0;
  240.                 Label_ lbVal = null;
  241.                 Label_ lbDesc = null;
  242.  
  243.                 int xDesc = 0, xVal=0;
  244.  
  245.                 for (int i = 0; i <= cols; i++)
  246.                 {
  247.                     mayorAnchoD = 0;
  248.                     mayorAnchoV = 0;
  249.  
  250.                     var consulta = from item in Lista where item.Columna == i && item.esDescripcion ==true select item;
  251.                     foreach (Label_ it in consulta)
  252.                     {
  253.                         if (it.Width > mayorAnchoD)
  254.                         {
  255.                             mayorAnchoD = it.Width;
  256.                             lbDesc = it;
  257.                         }
  258.                     }
  259.  
  260.                     var consulta2 = from item in Lista where item.Columna == i && item.esDescripcion == false select item;
  261.                     foreach (Label_ it in consulta2)
  262.                     {
  263.                         if (it.Width > mayorAnchoV)
  264.                         {
  265.                             mayorAnchoV = it.Width;
  266.                             lbVal = it;
  267.                         }
  268.                     }
  269.  
  270.                     foreach (Label_ it in consulta)
  271.                     {
  272.                         it.Location = new Point(xDesc + (mayorAnchoD - it.Width), it.Location.Y);
  273.                     }
  274.  
  275.                     foreach (Label_ it in consulta2)
  276.                     {
  277.                         it.Location = new Point(lbDesc.Right + 2, it.Location.Y);
  278.                     }
  279.  
  280.                     xDesc = lbVal.Right + 2;
  281.                    
  282.                 }
  283.             }
  284.         }
  285.     }
  286. }
  287.  
  288.  

3. El Designer del control anterior
Código: C#
  1. namespace ControlBarraDescripcion
  2. {
  3.     partial class BarraInformacion
  4.     {
  5.         /// <summary>
  6.         /// Variable del diseñador requerida.
  7.         /// </summary>
  8.         private System.ComponentModel.IContainer components = null;
  9.  
  10.         /// <summary>
  11.         /// Limpiar los recursos que se estén utilizando.
  12.         /// </summary>
  13.         /// <param name="disposing">true si los recursos administrados se deben eliminar; false en caso contrario, false.</param>
  14.         protected override void Dispose(bool disposing)
  15.         {
  16.             if (disposing && (components != null))
  17.             {
  18.                 components.Dispose();
  19.             }
  20.             base.Dispose(disposing);
  21.         }
  22.  
  23.         #region Código generado por el Diseñador de componentes
  24.  
  25.         /// <summary>
  26.         /// Método necesario para admitir el Diseñador. No se puede modificar
  27.         /// el contenido del método con el editor de código.
  28.         /// </summary>
  29.         private void InitializeComponent()
  30.         {
  31.             this.Pct = new System.Windows.Forms.PictureBox();
  32.             this.LbTITULO = new System.Windows.Forms.Label();
  33.             this.panel1 = new System.Windows.Forms.Panel();
  34.             ((System.ComponentModel.ISupportInitialize)(this.Pct)).BeginInit();
  35.             this.SuspendLayout();
  36.             //
  37.             // Pct
  38.             //
  39.             this.Pct.Location = new System.Drawing.Point(3, 25);
  40.             this.Pct.Name = "Pct";
  41.             this.Pct.Size = new System.Drawing.Size(97, 110);
  42.             this.Pct.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
  43.             this.Pct.TabIndex = 0;
  44.             this.Pct.TabStop = false;
  45.             //
  46.             // LbTITULO
  47.             //
  48.             this.LbTITULO.AutoSize = true;
  49.             this.LbTITULO.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold);
  50.             this.LbTITULO.Location = new System.Drawing.Point(3, 6);
  51.             this.LbTITULO.Name = "LbTITULO";
  52.             this.LbTITULO.Size = new System.Drawing.Size(113, 13);
  53.             this.LbTITULO.TabIndex = 1;
  54.             this.LbTITULO.Text = "Prueba con control";
  55.             //
  56.             // panel1
  57.             //
  58.             this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
  59.                         | System.Windows.Forms.AnchorStyles.Left)
  60.                         | System.Windows.Forms.AnchorStyles.Right)));
  61.             this.panel1.Location = new System.Drawing.Point(106, 25);
  62.             this.panel1.Name = "panel1";
  63.             this.panel1.Size = new System.Drawing.Size(518, 110);
  64.             this.panel1.TabIndex = 2;
  65.             //
  66.             // BarraInformacion
  67.             //
  68.             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
  69.             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  70.             this.Controls.Add(this.panel1);
  71.             this.Controls.Add(this.LbTITULO);
  72.             this.Controls.Add(this.Pct);
  73.             this.Font = new System.Drawing.Font("Tahoma", 8.25F);
  74.             this.Name = "BarraInformacion";
  75.             this.Size = new System.Drawing.Size(627, 138);
  76.             ((System.ComponentModel.ISupportInitialize)(this.Pct)).EndInit();
  77.             this.ResumeLayout(false);
  78.             this.PerformLayout();
  79.  
  80.         }
  81.  
  82.         #endregion
  83.  
  84.         private System.Windows.Forms.PictureBox Pct;
  85.         private System.Windows.Forms.Panel panel1;
  86.         public System.Windows.Forms.Label LbTITULO;
  87.     }
  88. }
  89.  
  90.  

4. Ejemplo de su Utilización
Código: C#
  1.  private void Trv_SelectedIndexChanged(object sender, EventArgs e)
  2.         {
  3.            
  4.  
  5.                 if (Trv.SelectedItems.Count == 1)
  6.                 {
  7.                     if (VariosSeleccionados)
  8.                     {
  9.                         CrearNuevasDescripciones = true;
  10.                         VariosSeleccionados = false;
  11.                     }
  12.                     else
  13.                     {
  14.                         CrearNuevasDescripciones = false;
  15.                     }
  16.  
  17.                     ListviewItemEstudiante item = (ListviewItemEstudiante)Trv.SelectedItems[0];
  18.  
  19.                     //determinar la mayor edad
  20.                     Single mayor = 0;
  21.                     for (int i = 1; i <= (Trv.Columns.Count - 2); i++)
  22.                     {
  23.  
  24.                         Single valor = 0;
  25.                         if (Trv.SelectedItems[0].SubItems[i].Text != "")
  26.                         {
  27.                             valor = Single.Parse(Trv.SelectedItems[0].SubItems[i].Text);
  28.                             if (valor > mayor)
  29.                             {
  30.                                 mayor = valor;
  31.                             }
  32.                         }
  33.                     }
  34.  
  35.                     if (CrearNuevasDescripciones)
  36.                     {
  37.                         barraInformacion1.Iniciar(Color.DimGray, Color.Black, "Actualmente usted ha seleccionado al estudiante: " + item.NombreCompleto.ToUpper(), -1);
  38.                     }
  39.  
  40.                     barraInformacion1.LbTITULO.Text = "Actualmente usted ha seleccionado al estudiante: " + item.NombreCompleto.ToUpper();
  41.                     barraInformacion1.AgregarDescripcion("ID", item.IDEstudiante.ToString("00000"), CrearNuevasDescripciones);
  42.                     barraInformacion1.AgregarDescripcion("Promedio", Trv.SelectedItems[0].SubItems[Trv.Columns.Count - 1].Text, CrearNuevasDescripciones);
  43.                     barraInformacion1.AgregarDescripcion("Tipo de documento", item.TipoDocumento, CrearNuevasDescripciones);
  44.                     barraInformacion1.AgregarDescripcion("Documento de Identidad", item.Documento, CrearNuevasDescripciones);
  45.                     barraInformacion1.AgregarDescripcion("Fecha de Nacimiento", item.FechaNacimiento.ToLongDateString(), CrearNuevasDescripciones);
  46.                     barraInformacion1.AgregarDescripcion("Ciudad Natal", item.CiudadNacimiento, CrearNuevasDescripciones);
  47.                     barraInformacion1.AgregarDescripcion("edad", item.Edad + " años", CrearNuevasDescripciones);
  48.                     barraInformacion1.AgregarDescripcion("Mayor Calificación", mayor.ToString() + " pts", CrearNuevasDescripciones);
  49.                     barraInformacion1.AgregarDescripcion("Sexo", item.Sexo, CrearNuevasDescripciones);
  50.                     barraInformacion1.AgregarDescripcion("Estado", item.Estado, CrearNuevasDescripciones);
  51.  
  52.                     if (!CrearNuevasDescripciones)
  53.                     {
  54.                         barraInformacion1.ReordenarItems();
  55.                     }
  56.  
  57.                 }
  58.                 else if (Trv.SelectedItems.Count > 1)
  59.                 {
  60.                     if (!VariosSeleccionados)
  61.                     {
  62.                         barraInformacion1.Iniciar(Color.DimGray, Color.Black, "Elementos Selccionados", -1);
  63.                         VariosSeleccionados = true;
  64.                         CrearNuevasDescripciones = true;
  65.                     }
  66.                     else
  67.                     {
  68.                         CrearNuevasDescripciones = false;
  69.                     }
  70.  
  71.                     int mayorEdad = 0, menorEdad = 0, acumEdad = 0;
  72.  
  73.                     Single promedio = 0, mayorPromedio = 0;
  74.                     ListviewItemEstudiante itMayor = null;
  75.                     ListviewItemEstudiante itMenor = null;
  76.                     ListviewItemEstudiante itMayorPromedio = null;
  77.                     int EstaEnLaPrimeraPosicion = 1;
  78.  
  79.                     foreach (ListviewItemEstudiante item in Trv.SelectedItems)
  80.                     {
  81.                         if (EstaEnLaPrimeraPosicion == 1)
  82.                         {
  83.                             menorEdad = item.Edad;
  84.                             itMenor = item;
  85.                             itMayorPromedio = item;
  86.                             EstaEnLaPrimeraPosicion = 0;
  87.                         }
  88.  
  89.                         if (item.promedio > mayorPromedio) { mayorPromedio = item.promedio; itMayorPromedio = item; }
  90.                         if (item.Edad > mayorEdad) { mayorEdad = item.Edad; itMayor = item; }
  91.                         if (item.Edad < menorEdad) { menorEdad = item.Edad; itMenor = item; }
  92.                         acumEdad += item.Edad;
  93.                     }
  94.  
  95.                     promedio = acumEdad / Trv.SelectedItems.Count;
  96.  
  97.  
  98.                     barraInformacion1.AgregarDescripcion("Seleccion", Trv.SelectedItems.Count.ToString(), CrearNuevasDescripciones);
  99.                     barraInformacion1.AgregarDescripcion("Mayor edad", itMayor.NombreCompleto + ", " + mayorEdad + " años", CrearNuevasDescripciones);
  100.                     barraInformacion1.AgregarDescripcion("Menor edad", itMenor.NombreCompleto + ", " + menorEdad + " años", CrearNuevasDescripciones);
  101.                     barraInformacion1.AgregarDescripcion("Promedio de edad", promedio.ToString() + " años", CrearNuevasDescripciones);
  102.                     barraInformacion1.AgregarDescripcion("Mejor promedio", itMayorPromedio.NombreCompleto + ", con " + mayorPromedio.ToString("0.00") + " pts", CrearNuevasDescripciones);
  103.                     if (!CrearNuevasDescripciones)
  104.                     {
  105.                         barraInformacion1.ReordenarItems();
  106.                     }
  107.  
  108.                
  109.             }
  110.         }
  111.  

y unas imágenes de como se ve en modo de ejecución
Título: Re: Código Barra de Información estilo Windows 7
Publicado por: cachorro en Domingo 16 de Mayo de 2010, 07:24
Q tal jeysscarr muy interesante tu trabajo...me pregunto si pudieras subir todo el proyecto para poder checarlo ya que me parecio interesante....