如何更改复选框上的检查图像

f1w*_*ade 10 .net c# checkbox winforms

它有文字,图像,然后是复选框,

我想使用更好的图像进行检查,但无法找到更改已检查和未检查图像的方法

this.checkBox1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.checkBox1.Checked = true;
this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox1.Image = global::ClientExam.Properties.Resources.action32;
this.checkBox1.Location = new System.Drawing.Point(145, 140);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(273, 127);
this.checkBox1.TabIndex = 0;
this.checkBox1.Text = "checkBox1";
this.checkBox1.TextImageRelation = System.Windows.Forms.TextImageRelation.TextBeforeImage;
this.checkBox1.UseVisualStyleBackColor = true;
Run Code Online (Sandbox Code Playgroud)

谁知道一个不要求我自己控制的人呢?

Ice*_*ind 10

如果您正在寻找如何在Winforms中执行此操作,简单的答案是创建一个派生自CheckBox的新复选框类,然后重写OnPaint方法.

以下是如何通过重写OnPaint方法创建自定义复选框的示例:

public class CustomCheckBox : CheckBox
{
    public CustomCheckBox()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
        this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    }

    protected override void OnPaint(PaintEventArgs pevent)
    {
        base.OnPaint(pevent);
        if (this.Checked)
        {
            pevent.Graphics.FillRectangle(new SolidBrush(Color.Blue), new Rectangle(0, 0, 16, 16));
        }
        else
        {
            pevent.Graphics.FillRectangle(new SolidBrush(Color.Red), new Rectangle(0, 0, 16, 16));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它非常简单,但它为您提供了基本的想法.


Kor*_*rli 7

对于那些不想重写OnPaint的人来说,还有另一种解决方案:

  1. 添加一个ImageList控件并用图像填充它以反映已检查/未检查的状态.
  2. Checkbox控件的Appearance属性设置为Button(以摆脱标准的CheckBox图标)
  3. 将其FlatStyle属性设置为Flat(以便控件看起来不像按钮).
    注意:您可能还想检查其" FlatAppearance属性组".也就是说CheckedBackColor,MouseDownBackColor,MouseOverBackColor,即它们都设置为Control值.
  4. Checkbox控件的ImageList属性设置为控件的名称ImageList.
  5. 设置Checkbox控件ImageindexImageAlign属性以反映其当前状态.
  6. 最后也是最重要的是设置Checkbox控件的TextImageRelation属性(除非你想要,否则这个值不会让文本和图像重叠).即ImageBeforetext值表示常见的CheckBox图标位置.

现在唯一要做的就是在状态改变时更改图像,如下所示:

    private void chkMyCheckBoxWithAnImage_CheckedChanged(object sender, EventArgs e)
    {
        if (chkMyCheckBoxWithAnImage.Checked)
            chkMyCheckBoxWithAnImage.ImageIndex = 1;
        else
            chkMyCheckBoxWithAnImage.ImageIndex = 0;
    }
Run Code Online (Sandbox Code Playgroud)

  • 在我看来这应该是答案。另一个答案没有提到除了图像之外您还必须处理绘制文本。 (3认同)
  • 您可以在没有图像列表的情况下执行完全相同的操作,只需直接在 CheckedChanged 事件中设置图像属性即可。 (2认同)