如何在 WinForms 中基于切换状态在切换按钮上绘制 Plus/Minus

How to draw a Plus/Minus on a Toggle Button based on Toggle State in WinForms

public partial class Form1 : Form
{
    CheckBoxExt checkBox;
    public Form1()
    {
        InitializeComponent();
        checkBox = new CheckBoxExt();
        this.Controls.Add(checkBox);
    }
}
public class CheckBoxExt : CheckBox
{
    public CheckBoxExt()
    {
        this.Size = new Size(20, 20);
        this.Location = new Point(200, 200);
        this.Appearance = Appearance.Button;
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        var point = this.PointToScreen(new Point(0, 0));
        e.Graphics.DrawLine(new Pen(ColorTranslator.FromHtml("#666666"), 2), new Point(point.X + 5, point.Y + 10), new Point(point.X + 15, point.Y + 10));
        if (this.Checked)
            e.Graphics.DrawLine(new Pen(ColorTranslator.FromHtml("#666666"), 2), new Point(point.X + 10, point.Y + 5), new Point(point.X + 10, point.Y + 15));
    }
    /// <summary>
    /// to remove the focus dotted border over the control
    /// </summary>
    protected override bool ShowFocusCues
    {
        get
        {
            return false;
        }
    }
}

这是我的代码,我自定义了 CheckBox 并将其外观设置为按钮,以便它充当切换按钮。

我需要画一条小水平线,在按钮上显示为减号,并画一条小水平线和垂直线,显示为加号按钮。因此,它需要切换,如果它处于选中状态,则需要显示加号,如果未选中,则需要在切换按钮上显示减号

提前致谢

我会使用 imageList 控件并分别用 plusminus 图像填充它,并具有所需的分辨率。

控件的BackgroundImage属性可以用来设置“+”和“-”图片

并且,不要忘记注册控件的 CheckedChanged 事件以切换控件的 BackgroundImage

例如这样的东西 -

    public Form1()
    {
        InitializeComponent();

        var checkBox = new CheckBoxExt();

        //My imageList contain two images, for "+" and "-"

        //Register chacked changed event for the control
        checkBox.CheckedChanged += checkBox_CheckedChanged;

        //Set the initial image as "-"
        checkBox.BackgroundImage = this.imageList1.Images[1];

        this.Controls.Add(checkBox);
    }

    void checkBox_CheckedChanged(object sender, EventArgs e)
    {
        if (((CheckBox)sender).Checked)
        {
            ((CheckBox)sender).BackgroundImage = this.imageList1.Images[0];
        }
        else
        {
            ((CheckBox)sender).BackgroundImage = this.imageList1.Images[1];
        }
    }