2013-11-21 21 views
1

我有一個自定義面板設計爲能夠顯示純色背景色,漸變背景色或圖片。陷入一個OnPaint循環與從面板派生的自定義控件

我重寫既BackgroundImage屬性和OnPaint方法如下所示:

protected override void OnPaint(PaintEventArgs pe){ 
    Rectangle rc = new Rectangle(0, 0, this.Width, this.Height); 
    if (this.DrawStyle != DrawStyle.Picture){ 
     base.BackgroundImage = null; 

      if (this.DrawStyle == DrawStyle.Solid){ 
       using (SolidBrush brush = new SolidBrush(this.PrimaryColor)) 
        pe.Graphics.FillRectangle(brush, rc); 
      } 
      else if (this.DrawStyle == DrawStyle.Gradient){ 
       using (LinearGradientBrush brush = 
         new LinearGradientBrush(
          rc, this.PrimaryColor, this.SecondaryColor, this.Angle)) 
       pe.Graphics.FillRectangle(brush, rc); 
      } 
     } 
    else if (this._BGImage != null) 
     base.BackgroundImage = this._BGImage; 
} 

public override Image BackgroundImage{ 
    get { return this._BGImage; } 
    set { this._BGImage = value; } 
} 

其原因是在於,控制必須足夠靈活期間改變的背景類型(固體,梯度或圖片)運行時間,因此控制會保留在設定的背景圖像上並在必要時顯示。

但是,我遇到了問題。

如果我沒有設置背景圖像,沒有問題。 OnPaint被調用大約5次,然後它很好。

但是,當我設置背景圖像時,它似乎變得瘋狂,一遍又一遍地調用OnPaint。

這很明顯與覆蓋背景圖像有關,這是一個問題,因爲它會掛起,面板上的任何內容都不會更新,直到我更改面板外觀。

所以我想我的問題是爲什麼當我設置背景圖像時它陷在這個OnPaint循環中?

+0

由於最新更新刪除了實際問題,因此我將帖子轉回原始問題。 – LarsTech

回答

2

評論了這一點:

// base.BackgroundImage = this._BGImage; 

這導致了它遞歸油漆本身。你不應該在繪畫例程中設置屬性。

此外,你沒有通過重寫BackgroundImage來完成任何事情,如果你重寫屬性,那應該是你賦值base.BackgroundImage值的唯一地方。考慮刪除它。

我返工你的代碼是:

protected override void OnPaintBackground(PaintEventArgs e) { 
    if (this.DrawStyle == DrawStyle.Picture) { 
    base.OnPaintBackground(e); 
    } 
} 

protected override void OnPaint(PaintEventArgs e) { 
    Rectangle rc = this.ClientRectangle; 
    if (this.DrawStyle == DrawStyle.Solid) { 
    using (SolidBrush brush = new SolidBrush(this.PrimaryColor)) 
     e.Graphics.FillRectangle(brush, rc); 
    } else if (this.DrawStyle == DrawStyle.Gradient) { 
    using (LinearGradientBrush brush = 
      new LinearGradientBrush(
       rc, this.PrimaryColor, this.SecondaryColor, this.Angle)) 
     e.Graphics.FillRectangle(brush, rc); 
    } 
    base.OnPaint(e); 
} 

確保添加this.DoubleBuffered = true;this.ResizeRedraw = true;在面板的構造,以避免不必要的閃爍。

+0

好的,謝謝。我找到了解決方法。編輯以反映變化。 – Will

+0

@我不會在你的繪畫中調用'base.BackgroundImage = null;'。 – LarsTech

+0

你能告訴那個人在他的財產創造者中分配base.BackgroundImage嗎? –