【问题标题】:How do I group together radio buttons that are in a custom control?如何将自定义控件中的单选按钮组合在一起?
【发布时间】:2013-09-30 08:18:56
【问题描述】:

我有一个基于单选按钮的自定义控件(不是组件),该按钮有一个花哨的标签,当标签被选中时会发出绿色,当它不是为了提供更好的视觉反馈时会发出黑色,因为为什么不呢。

为了确认我的恐惧,我在表单上放了一堆并运行它,果然,它们不被视为“组合在一起”,因为我可以激活所有它们,而其他任何一个都不会停用。

我如何才能使这些控件中的每一个都成为“特殊单选按钮组”的一部分并像普通单选按钮一样工作?

【问题讨论】:

  • WinForms?你是从 RadioButton 继承的吗?
  • 我没有。如果我知道我可以让它工作,但我在标准标签上使用了一个特殊标签 (gLabel),并且不知道如何将它放在标准标签上。这可能是一个理想的解决方案......

标签: winforms c#-4.0 radio-button custom-controls grouping


【解决方案1】:

好的,我找到了“A”解决方案。我不知道这是否是一个理想的解决方案,但它有效。

我已经关闭了寻找“CheckedChanged”事件的对象功能。问题是无论是手动完成还是以编程方式完成都会触发。 解决方案?使用“点击”事件。但不仅仅是在按钮上,在整个事情上。

所以我们得到的是这样的:

namespace Pieces{
public partial class ucGraphicLabelRadioButton : UserControl{
    private event EventHandler _CheckedChanged;

    /// <summary>
    /// Gets or sets the controls text.
    /// </summary>
    public override string Text{
        get{return this.lblTitle.Text;}
        set{lblTitle.Text = value;}
    }
    /// <summary>
    /// Gets or sets the checked state of the button.
    /// </summary>
    public bool Checked{
        get{return this.rbtnButton.Checked;}
        set{this.rbtnButton.Checked = value;}
    }

    public event EventHandler CheckedChanged{
        add{this._CheckedChanged += value;}
        remove{this._CheckedChanged -= value;}
    }

    public ucGraphicLabelRadioButton(){
        InitializeComponent();
    }

    //This is where the fancy stuff happens...
    private void ToggleCheck(object sender, EventArgs e){
        this.lblTitle.GlowColor = Color.Green;
        bool FoundOtherChecked = false;
        this.Parent.Controls.OfType<ucGraphicLabelRadioButton>().Where(x => x.Checked && x != this).ToList().ForEach(x => {
            x.Checked = false;
            x.lblTitle.GlowColor = Color.Black;
            FoundOtherChecked = true;
        });

        if ((FoundOtherChecked && !this.Checked) || !this.Checked){
            this.Checked = !this.Checked;            
            this.lblTitle.GlowColor = this.rbtnButton.Checked ? Color.Green : Color.Black;
        }

        if (this._CheckedChanged != null)
            this._CheckedChanged(this, new EventArgs());
    }
}

}

“ToggleCheck”事件与 RadioButton 对象的“Click”事件以及标签的“Click”事件和整个自定义控件的“Click”事件相关联,因此理想情况下,单击标签上的任意位置都会触发该事件。

当对象被切换时,它会在父控件中运行 linq 搜索与自身相似的任何对象,并且仅在选中时才抓取它。然后,它取消选中它并将发光状态设置为黑色。

该控件还有一个事件,可以将您想要绑定到单选按钮“CheckedChanged”事件的任何类型的事件转发,然后触发它。

我知道做整个

.ToList().ForEach(x => ...)

完全是矫枉过正,因为搜索只会返回一个对象(或者在它自行关闭的情况下不会返回一个对象),但它确实有效。有没有更好的方法来做到这一点?

编辑:我必须进行一些更改,因为显然当您直接单击单选按钮时,它会首先被选中,然后触发 clicked 事件。此外,为了确保它们的行为更像单选按钮,而不像具有单选按钮行为的复选框,即:用户现在无法单击它们。它会在自己关闭之前检查是否已打开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-28
    • 2013-05-08
    • 2014-12-03
    • 2020-11-24
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多