我有一個自定義面板設計爲能夠顯示純色背景色,漸變背景色或圖片。陷入一個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循環中?
由於最新更新刪除了實際問題,因此我將帖子轉回原始問題。 – LarsTech