首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

設計支援圖示與自訂顏色的 ListBox (3):核心繪製邏輯 OnDrawItem

     編輯:關於C語言

支援圖示:加入 ImageList

private ImageList imageList;
public ImageList ImageList
{
    get { return this.imageList; }
    set
    {
        this.imageList = value;
        this.Invalidate(); // 圖像列表改變後立即更新控制項
    }
}

核心繪製方法:OnDrawItem

此控制項核心在 OnDrawItem,每當控制項項目需要重繪時被呼叫:

protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs pe)
{
    pe.DrawBackground();        // 畫背景
    pe.DrawFocusRectangle();    // 畫焦點矩形
    Rectangle bounds = pe.Bounds;

    // 檢查索引有效性
    if (pe.Index >= 0 && pe.Index < base.Items.Count)
    {
        ListBoxExItem item = this.Items[pe.Index]; // 取得需繪製項目參考
        int iOffset = 0;

        // 若有 ImageList 且設定 ImageIndex,繪製圖示
        if (this.imageList != null)
        {
            if (item.ImageIndex > -1 && item.ImageIndex < this.imageList.Images.Count)
            {
                this.imageList.Draw(pe.Graphics, bounds.Left, bounds.Top, 
                    bounds.Height, bounds.Height, item.ImageIndex); // 繪製圖示
            }
            iOffset += bounds.Height; // this.imageList.ImageSize.Width;
        }

        // 繪製項目文字,依項目顏色
        pe.Graphics.DrawString(item.Text, pe.Font, 
            new SolidBrush(item.ForeColor), bounds.Left + iOffset, bounds.Top);
    }
    base.OnDrawItem(pe);
}

至此 ListBoxEx 完整實現,並支援視覺化設計。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved