2015/2/7

【C#】客製化外觀的三態按鈕(Three State CheckBox)

.NET提供的CheckBox元件本身就支援三態按鈕(三種選取狀態),只要把屬性ThreeState設定為True即可
但有時候預設的外觀顯示與操作體驗可能無法準確呈現使用情境,這時可以新建一個類別繼承CheckBox並重載OnPaint與OnClick方法來客製化符合使用情境的三態按鈕
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class CheckBoxTriState : CheckBox
{
    public CheckBoxTriState()
    {
        ThreeState = true;
        CheckState = System.Windows.Forms.CheckState.Indeterminate;
        Text = String.Empty;
        Size = new Size(20, 40);
    }

    protected override void OnPaint(PaintEventArgs pevent)
    {
        Graphics g = pevent.Graphics;
        g.Clear(Color.LightGray);
        Brush b = new SolidBrush(Color.DarkGray);
        g.DrawRectangle(new Pen(b), 0, 0, Width, Height);

        float radius = (float)(Width * 0.9);
        float margin = (float)(Width * 0.05);
        if (CheckState == System.Windows.Forms.CheckState.Indeterminate)
            g.FillEllipse(b, margin, (float)(Height / 4.0) + margin, radius, radius);
        else if (CheckState == System.Windows.Forms.CheckState.Checked)
            g.FillEllipse(b, margin, margin, radius, radius);
        else
            g.FillEllipse(b, margin, (float)(Height / 2.0 - margin), radius, radius);
    }

    protected override void OnClick(EventArgs e)
    {
        Point pos = this.PointToClient(Cursor.Position);
        if (pos.Y < Height / 3)
            CheckState = System.Windows.Forms.CheckState.Checked;
        else if (pos.Y > Height * 2 / 3)
            CheckState = System.Windows.Forms.CheckState.Unchecked;
        else
            CheckState = System.Windows.Forms.CheckState.Indeterminate;
    }
}
使用方始與一般的CheckBox相同
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        CheckBoxTriState check = new CheckBoxTriState();
        check.Location = new Point(10, 10);
        Controls.Add(check);

        CheckBoxTriState check2 = new CheckBoxTriState();
        check2.Location = new Point(40, 10);
        check2.CheckState = CheckState.Checked;
        Controls.Add(check2);

        CheckBoxTriState check3 = new CheckBoxTriState();
        check3.Location = new Point(70, 10);
        check3.CheckState = CheckState.Unchecked;
        Controls.Add(check3);
    }
}
Keyword:How to customize a tri-state checkbox / button in C#

沒有留言:

張貼留言