c# 創建自繪用戶控件


一、繼承UserControl類

public class Chart : UserControl

 

二、定義常量、私有成員變量、屬性

  加入屬性的修飾,可以在圖形界面配置

  private const int LeftPos = 60;

  private int[] m_values = new int[3];

  [CategoryAttribute("Chart")]   [DescriptionAttribute("已解決的事務數量")]
  [DefaultValueAttribute(0)]   public int Resolved
  {   get {   return m_values[0];     } set {   //對輸入值進行驗證 if (value < 0) {   value = 0; } m_values[0] = value; //重繪控件 Invalidate();     }   }

 三、重寫父類UserControl的幾個事件處理

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    e.Graphics.Clear(Parent.BackColor);
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    //如果控件大小能顯示下所有數據
    if (Width > LeftPos && m_barHeight > 1)
    {
        //繪制左邊的標簽
        DrawLabels(e.Graphics);
        //繪制圖表
        DrawChart(e.Graphics);
    }
    // 總是繪制文本信息
    DrawMessage(e.Graphics);
}

protected override void OnSizeChanged(EventArgs e)
{
    // 調用CalculateBounds函數重新計算布局
    CalculateBounds();
    
    //調用基類處理函數
    base.OnSizeChanged(e);
}

// 計算布局及布局內元素的各種參數數值
private void CalculateBounds()
{ 
}

protected override void OnFontChanged(EventArgs e)
{
    base.OnFontChanged(e);
    CalculateBounds();
}

protected override void OnTextChanged(EventArgs e)
{
    base.OnTextChanged(e);
    CalculateBounds();
    // 立刻重繪
    Invalidate();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM