![](/img/trans.png)
[英]Disabling a button in a panel triggers CheckedChanged event on radio buttons in panel
[英]Radio button CheckedChanged event only when checked?
情況
我只想當單選按鈕被選中時有一個事件。
我知道選中和取消選中單選按鈕時會調用事件CheckedChanged事件,我知道原因。 我知道如何使用它僅在選中時執行代碼。 請參閱: 單選按鈕選中的更改事件觸發兩次
題
但是我使用了其他語言,這些語言在單選按鈕被選中時會發生事件(未選中時不會被調用)。 是否有這樣的事件可以直接在C#中執行
(要知道是否有特定的事件,通常是一個是或否的問題,因為我知道我可以檢查該事件) ?
據我所知。 您最好這樣做:
var radioButton = sender as RadioButton;
if (radioButton == null || !radioButton.Checked) return;
// your code ...
當頁面回發時,您可以在頁面事件中更改單選按鈕的事件處理程序。 為此,您需要使用VIEWSTATE中的Radiobutton值,然后分配事件處理程序。
一種通用的解決方法是使用樣式為單選按鈕的列表框,以防止必須使用多個綁定/控件/選中復選框。 只有一個控件需要監視哪個事件( SelectedIndexChanged
),而不是檢查選中了哪個單選按鈕,而是使用SelectedItem
。 另一個優點是能夠綁定數據源,而不是動態添加單選按鈕。
為此,這里有一個簡單的RadioButtonBox
控件,它就是這樣做的(很久以前就做了,從那以后就沒有修改過,但仍然定期使用)
public class RadioButtonBox:ListBox
{
public readonly RadioButtonBoxPainter Painter;
public RadioButtonBox()
{
Painter = new RadioButtonBoxPainter(this);
}
[DefaultValue(DrawMode.OwnerDrawFixed)]
public override DrawMode DrawMode
{
get{return base.DrawMode;}
set{base.DrawMode = value;}
}
}
public class RadioButtonBoxPainter : IDisposable
{
public readonly ListBox ListBox;
public RadioButtonBoxPainter(ListBox ListBox)
{
this.ListBox = ListBox;
ListBox.DrawMode = DrawMode.OwnerDrawFixed;
ListBox.DrawItem += ListBox_DrawItem;
}
void ListBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == -1) return;
Rectangle r = e.Bounds;
r.Width = r.Height;
bool selected = (e.State & DrawItemState.Selected) > 0;
e.DrawBackground();
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
ControlPaint.DrawRadioButton(e.Graphics, r, selected ? ButtonState.Checked : ButtonState.Normal);
r.X = r.Right + 2;
r.Width = e.Bounds.Width - r.X;
string txt;
if (ListBox.Site != null && ListBox.Site.DesignMode && e.Index >= ListBox.Items.Count)
txt = ListBox.Name;
else
txt = ListBox.GetItemText(ListBox.Items[e.Index]);
using (var b = new SolidBrush(e.ForeColor))
e.Graphics.DrawString(txt, e.Font, b, r);
if (selected)
{
r = e.Bounds;
r.Width--; r.Height--;
e.Graphics.DrawRectangle(Pens.DarkBlue, r);
}
}
public void Dispose()
{
ListBox.DrawItem -= ListBox_DrawItem;
}
}
RadioButtonBox
是控件, RadioButtonBoxPainter
是執行自定義繪畫的類,可以在任何ListBox上使用(繪畫也可以集成到控件中,但是一開始它是為了使某些現有列表框具有單選按鈕外觀) 。
至於顯示,通常它仍然具有該列表框的感覺:
但是通過將backcolor設置為“ Control”並且沒有邊框樣式,結果看起來像常規單選按鈕:
如果總是首選第二種布局,則可以始終在RadioButtonBox控件中將它們設置為默認設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.