在C#中,復選框控件通常只能顯示默認的勾選圖標和文本。但是,你可以通過繼承復選框控件并重寫其繪制方法來實現自定義的圖標和文本顯示。
以下是一個簡單的示例代碼,演示如何繼承復選框控件并自定義其圖標和文本:
using System;
using System.Drawing;
using System.Windows.Forms;
public class CustomCheckBox : CheckBox
{
private Image customIcon;
public Image CustomIcon
{
get { return customIcon; }
set
{
customIcon = value;
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
if (customIcon != null)
{
pevent.Graphics.DrawImage(customIcon, new Point(0, 0));
}
// Custom text display
TextRenderer.DrawText(pevent.Graphics, Text, Font, new Rectangle(ClientRectangle.X + 20, ClientRectangle.Y, ClientRectangle.Width - 20, ClientRectangle.Height), ForeColor);
}
}
在這個自定義的復選框控件中,我們添加了一個CustomIcon
屬性用于設置自定義圖標。在OnPaint
方法中,我們先繪制自定義圖標,然后再繪制文本。你可以根據自己的需求來調整圖標和文本的位置和樣式。
使用這個自定義的復選框控件,你可以輕松地實現自定義圖標和文本顯示的效果。