Pregunta

Sé que WebForms tiene un control RadioButtonList , pero no puedo encontrar uno para WinForms . Lo que necesito es tener 3 RadioButtons agrupados, de modo que solo se pueda seleccionar 1 a la vez. Estoy descubriendo que tengo que hacer esto a través del código, lo cual es una molestia. ¿No estoy viendo RadioButtonList en alguna parte, o realmente no existe en WinForms ?

¿Fue útil?

Solución

Aparentemente no .

Puede agrupar tres RadioButtons juntos usando un GroupBox o un Panel como se hace aquí .

Otros consejos

Si solo desea agrupar botones de radio, es suficiente colocarlos en un contenedor, entonces actuarán como un grupo, pero si necesita un enlace de datos como un ComboBox o ListBox o CheckedListBox funciona, necesita un control RadioButtonList .

Los formularios de Windows no tienen un control RadioButtonList incorporado. Puede crear su propio control derivando el formulario ListBox y haciendo que el propietario dibuje y dibuje los botones de selección usted mismo. Esta es la forma en que también se crea CheckedListBox .

De esta forma, el control admite el enlace de datos y se beneficiará de todas las características de ListBox , incluyendo DataSource , SelectedValue , DisplayMember , ValueMember y así sucesivamente. Por ejemplo, simplemente puede usarlo de esta manera:

this.radioButtonList1.DataSource = peopleTable; 
this.radioButtonList1.DisplayMember = "Name"; 
this.radioButtonList1.ValueMember= "Id";

O, por ejemplo, para una enum , simplemente de esta manera:

this.radioButtonList1.DataSource = Enum.GetValues(typeof(DayOfWeek)); 

En la imagen de abajo, la segunda RadioButtonList se deshabilita configurando Enabled = false; :

 ingrese la descripción de la imagen aquí ingrese la descripción de la imagen aquí

También el control admite de derecha a izquierda también:

 ingrese la descripción de la imagen aquí

También admite columnas múltiples:

 ingrese la descripción de la imagen aquí

RadioButtonList

Aquí está el código fuente para el control. Puede usarlo como un ListBox normal agregando elementos o configurando la fuente de datos con / sin usar enlace de datos:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
public class RadioButtonList : ListBox
{
    Size s;
    public RadioButtonList()
    {
        this.DrawMode = DrawMode.OwnerDrawFixed;
        using (var g = Graphics.FromHwnd(IntPtr.Zero))
            s = RadioButtonRenderer.GetGlyphSize(
                Graphics.FromHwnd(IntPtr.Zero), RadioButtonState.CheckedNormal);
    }
    protected override void OnDrawItem(DrawItemEventArgs e)
    {

        var text = (Items.Count > 0) ? GetItemText(Items[e.Index]) : Name;
        Rectangle r = e.Bounds; Point p;
        var flags = TextFormatFlags.Default | TextFormatFlags.NoPrefix;
        var selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;
        var state = selected ?
            (Enabled ? RadioButtonState.CheckedNormal : 
                       RadioButtonState.CheckedDisabled) :
            (Enabled ? RadioButtonState.UncheckedNormal : 
                       RadioButtonState.UncheckedDisabled);
        if (RightToLeft == System.Windows.Forms.RightToLeft.Yes)
        {
            p = new Point(r.Right - r.Height + (ItemHeight - s.Width) / 2,
                r.Top + (ItemHeight - s.Height) / 2);
            r = new Rectangle(r.Left, r.Top, r.Width - r.Height, r.Height);
            flags |= TextFormatFlags.RightToLeft | TextFormatFlags.Right;
        }
        else
        {
            p = new Point(r.Left + (ItemHeight - s.Width) / 2,
            r.Top + (ItemHeight - s.Height) / 2);
            r = new Rectangle(r.Left + r.Height, r.Top, r.Width - r.Height, r.Height);
        }
        var bc = selected ? (Enabled ? SystemColors.Highlight : 
            SystemColors.InactiveBorder) : BackColor;
        var fc = selected ? (Enabled ? SystemColors.HighlightText : 
            SystemColors.GrayText) : ForeColor;
        using (var b = new SolidBrush(bc))
            e.Graphics.FillRectangle(b, e.Bounds);
        RadioButtonRenderer.DrawRadioButton(e.Graphics, p, state);
        TextRenderer.DrawText(e.Graphics, text, Font, r, fc, bc, flags);
        e.DrawFocusRectangle();
        base.OnDrawItem(e);
    }
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override SelectionMode SelectionMode
    {
        get { return System.Windows.Forms.SelectionMode.One; }
        set { }
    }
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override int ItemHeight
    {
        get { return (this.Font.Height + 2); }
        set { }
    }
    [EditorBrowsable(EditorBrowsableState.Never), Browsable(false),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override DrawMode DrawMode
    {
        get { return base.DrawMode; }
        set { base.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; }
    }
}

El simple hecho de que varios botones de radio están en el mismo contenedor los hace mutuamente excluyentes, no tiene que codificar este comportamiento usted mismo. Simplemente colóquelos en un Panel o GroupBox como sugiere Matthew

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top