一、繼承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(); }