using System; using System.Linq; namespace Gwen.Control { /// /// Radio button group. /// public class RadioButtonGroup : GroupBox { private LabeledRadioButton m_Selected; /// /// Selected radio button. /// public LabeledRadioButton Selected { get { return m_Selected; } } /// /// Internal name of the selected radio button. /// public String SelectedName { get { return m_Selected.Name; } } /// /// Text of the selected radio button. /// public String SelectedLabel { get { return m_Selected.Text; } } /// /// Index of the selected radio button. /// public int SelectedIndex { get { return Children.IndexOf(m_Selected); } } /// /// Invoked when the selected option has changed. /// public event GwenEventHandler SelectionChanged; /// /// Initializes a new instance of the class. /// /// Parent control. /// Label for the outlining GroupBox. public RadioButtonGroup(Base parent, String label) : base(parent) { IsTabable = false; KeyboardInputEnabled = true; Text = label; AutoSizeToContents = true; } /// /// Adds a new option. /// /// Option text. /// Newly created control. public virtual LabeledRadioButton AddOption(String text) { return AddOption(text, String.Empty); } /// /// Adds a new option. /// /// Option text. /// Internal name. /// Newly created control. public virtual LabeledRadioButton AddOption(String text, String optionName) { LabeledRadioButton lrb = new LabeledRadioButton(this); lrb.Name = optionName; lrb.Text = text; lrb.RadioButton.Checked += OnRadioClicked; lrb.Dock = Pos.Top; lrb.Margin = new Margin(0, 0, 0, 1); // 1 bottom lrb.KeyboardInputEnabled = false; // todo: true? lrb.IsTabable = true; Invalidate(); return lrb; } /// /// Handler for the option change. /// /// Event source. protected virtual void OnRadioClicked(Base fromPanel) { RadioButton @checked = fromPanel as RadioButton; foreach (LabeledRadioButton rb in Children.OfType()) // todo: optimize { if (rb.RadioButton == @checked) m_Selected = rb; else rb.RadioButton.IsChecked = false; } OnChanged(); } /* /// /// Sizes to contents. /// public override void SizeToContents() { RecurseLayout(Skin); // options are docked so positions are not updated until layout runs //base.SizeToContents(); int width = 0; int height = 0; foreach (Base child in Children) { width = Math.Max(child.Width, width); height += child.Height; } SetSize(width, height); InvalidateParent(); } */ protected virtual void OnChanged() { if (SelectionChanged != null) SelectionChanged.Invoke(this); } /// /// Selects the specified option. /// /// Option to select. public void SetSelection(int index) { if (index < 0 || index >= Children.Count) return; (Children[index] as LabeledRadioButton).RadioButton.Press(); } } }