2013-01-18 110 views
0

我有一個UserControl,其上有一個button。在UserControlOnPaint事件中,我繪製了一個圓角邊框(如果半徑爲零,則繪製一個簡單的矩形),然後填充整個控件。在這些操作之後,我的ButtonbtnClose)消失。 如何使我的button再次可見?UserControl的OnRepaint事件後,控件從父UserControl中消失

protected override void OnPaint(PaintEventArgs pe) 
{ 
    using (System.Drawing.Pen p = new Pen(new SolidBrush(this.BorderColor))) 
    { 
     if (borderRadius > 0) 
     { 
      DrawRoundRect(pe.Graphics, p, 0, 0, this.Width - 1, this.Height - 1, borderRadius, this.FillColor); 
     } 
     else 
     { 
      this.BackColor = this.FillColor; 
      pe.Graphics.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1); 
     } 
     btnClose.Location = new Point(this.Width - btnClose.Width - BTN_MARGIN_DELTA, BTN_MARGIN_DELTA); 
    } 
    base.OnPaint(pe); 
} 

以防萬一,在DrawRoundRect功能:

void DrawRoundRect(Graphics g, Pen p, float X, float Y, float width, float height, float radius, Color _fillColor) 
{ 
    using (GraphicsPath gp = new GraphicsPath()) 
    { 
     gp.AddLine(X + radius, Y, X + width - (radius * 2), Y); 
     gp.AddArc(X + width - (radius * 2), Y, radius * 2, radius * 2, 270, 90); 
     gp.AddLine(X + width, Y + radius, X + width, Y + height - (radius * 2)); 
     gp.AddArc(X + width - (radius * 2), Y + height - (radius * 2), radius * 2, radius * 2, 0, 90); 
     gp.AddLine(X + width - (radius * 2), Y + height, X + radius, Y + height); 
     gp.AddArc(X, Y + height - (radius * 2), radius * 2, radius * 2, 90, 90); 
     gp.AddLine(X, Y + height - (radius * 2), X, Y + radius); 
     gp.AddArc(X, Y, radius * 2, radius * 2, 180, 90); 
     gp.CloseFigure(); 

     using (SolidBrush brush = new SolidBrush(_fillColor)) 
     { 
      g.FillPath(brush, gp); 
      g.DrawPath(p, gp); 
     } 
    } 
} 

回答

1

嘗試的位置代碼移到大小調整方法:

protected override void OnResize(EventArgs e) { 
    btnClose.Location = new Point(this.Width - btnClose.Width - BTN_MARGIN_DELTA, BTN_MARGIN_DELTA); 
} 

移動控制在油漆事件可能導致遞歸調用繪畫事件。只在繪畫事件中「繪畫」。

+0

那麼,這是我的錯誤。這是一個從UserControl中刪除所有控件的函數。代碼如下所示。 @LarsTech,無論如何,謝謝,OnResize幫助建立了按鈕的正確位置。 – kirpi4

0

我設置了FillColor = Color.Gray,BorderColor = Color.Black,borderRadius = 5,BTN_MARGIN_DELTA = 2它似乎沒有任何問題。下面是截圖:

enter image description here

我覺得這個問題是不是這幾行代碼。

+0

好的,舒爾。問題出在其他地方,我完全刪除了控件。 – kirpi4

0

好吧,我的錯。這是一個從UserControl中刪除所有控件的函數。所以我過濾刪除的控件。

void ClearControls() 
{ 
    for (int i = 0; i < Items.Count; i++) 
    { 
     foreach (Control cc in Controls) 
     { 
      if (cc.Name.Contains(LINK_LABEL_FAMILY) || (cc.Name.Contains(LABEL_FAMILY))) 
      { 
       Controls.RemoveByKey(cc.Name); 
      } 
     } 
    } 
} 
相關問題