gpt4 book ai didi

c# - WinForms 中单选按钮列表的第三方控件?

转载 作者:太空宇宙 更新时间:2023-11-03 19:33:39 25 4
gpt4 key购买 nike

是否有任何控件可以根据对象列表动态创建一组单选按钮?类似于 CheckedBoxList 控件,但具有互斥选择。 This question指出 WinForms native 不存在此控件,但是否有任何第三方控件可以执行此操作?

最佳答案

控件供应商不能通过这样的控件赚到钱。下面是一些入门代码:

using System;
using System.Drawing;
using System.Windows.Forms;

class RadioList : ListBox {
public event EventHandler SelectedOptionChanged;

public RadioList() {
this.DrawMode = DrawMode.OwnerDrawFixed;
this.ItemHeight += 2;
}
public int SelectedOption {
// Current item with the selected radio button
get { return mSelectedOption; }
set {
if (value != mSelectedOption) {
Invalidate(GetItemRectangle(mSelectedOption));
mSelectedOption = value;
OnSelectedOptionChanged(EventArgs.Empty);
Invalidate(GetItemRectangle(value));
}
}
}
protected virtual void OnSelectedOptionChanged(EventArgs e) {
// Raise SelectOptionChanged event
EventHandler handler = this.SelectedOptionChanged;
if (handler != null) handler(this, e);
}
protected override void OnDrawItem(DrawItemEventArgs e) {
// Draw item with radio button
using (var br = new SolidBrush(this.BackColor))
e.Graphics.FillRectangle(br, e.Bounds);
if (e.Index < this.Items.Count) {
Rectangle rc = new Rectangle(e.Bounds.Left, e.Bounds.Top, e.Bounds.Height, e.Bounds.Height);
ControlPaint.DrawRadioButton(e.Graphics, rc,
e.Index == SelectedOption ? ButtonState.Checked : ButtonState.Normal);
rc = new Rectangle(rc.Right, e.Bounds.Top, e.Bounds.Width - rc.Right, e.Bounds.Height);
TextRenderer.DrawText(e.Graphics, this.Items[e.Index].ToString(), this.Font, rc, this.ForeColor, TextFormatFlags.Left);
}
if ((e.State & DrawItemState.Focus) != DrawItemState.None) e.DrawFocusRectangle();
}
protected override void OnMouseUp(MouseEventArgs e) {
// Detect clicks on the radio button
int index = this.IndexFromPoint(e.Location);
if (index >= 0 && e.X < this.ItemHeight) SelectedOption = index;
base.OnMouseUp(e);
}
protected override void OnKeyDown(KeyEventArgs e) {
// Turn on option with space bar
if (e.KeyData == Keys.Space && this.SelectedIndex >= 0) SelectedOption = this.SelectedIndex;
base.OnKeyDown(e);
}
private int mSelectedOption;
}

关于c# - WinForms 中单选按钮列表的第三方控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3408175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com