好的,我找到了“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 事件。此外,为了确保它们的行为更像单选按钮,而不像具有单选按钮行为的复选框,即:用户现在无法单击它们。它会在自己关闭之前检查是否已打开。