2016-02-24 77 views
1

我已經創建了兩個自定義面板(ParentPanel和ChildPanel)並添加了ChildPanel作爲ParentPanel的子級。現在我想單獨使子面板無效。但同時呼籲ChildPanel.Invalidate(),OnPaint方法已經要求兩個面板(ParentPanel和ChildPanel)。如何在Windows窗體中獨自使子面板失效?

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     private ParentPanel parentPanel; 
     public Form1() 
     { 
     InitializeComponent(); 

     parentPanel = new ParentPanel(); 
     parentPanel.Size = new Size(300, 200); 
     parentPanel.Location = new Point(3,30); 

     var button1 = new Button(); 
     button1.Text = "Invalidate Child"; 
     button1.Size = new Size(130, 25); 
     button1.Location = new Point(3,3); 
     button1.Click += button1_Click; 

     this.Controls.Add(parentPanel); 
     this.Controls.Add(button1); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     this.parentPanel.ChildPanel.Invalidate(); 
    } 
} 

public class ParentPanel : Panel 
{ 
    public ChildPanel ChildPanel { get; set; } 

    public ParentPanel() 
    { 
     BackColor = Color.Yellow; 
     ChildPanel = new ChildPanel(); 
     this.Controls.Add(ChildPanel); 

     SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.Selectable | 
       ControlStyles.UserPaint | 
       ControlStyles.AllPaintingInWmPaint, true); 
    } 

    protected override void OnPaint(PaintEventArgs e) 
    { 
     MessageBox.Show("Parent Panel invalidated"); 
     base.OnPaint(e); 
    } 
} 

public class ChildPanel : Panel 
{ 
    public ChildPanel() 
    { 
     BackColor = Color.Transparent; 
     Anchor = AnchorStyles.Left | AnchorStyles.Top; 
     Dock = DockStyle.Fill; 

     SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.Selectable | 
       ControlStyles.UserPaint | 
       ControlStyles.AllPaintingInWmPaint, true); 

    } 

    protected override void OnPaint(PaintEventArgs e) 
    { 
     MessageBox.Show("Child Panel Invalidated"); 
    } 
} 
} 

我曾嘗試用WM_SETREDRAW跳過ParentPanel的繪製。但它會暫停兩個面板的繪製。

[DllImport("user32.dll")] 
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam); 

private const int WM_SETREDRAW = 11; 

public static void SuspendDrawing(Control parent) 
{ 
    SendMessage(parent.Handle, WM_SETREDRAW, false, 0); 
} 

public static void ResumeDrawing(Control parent) 
{ 
    SendMessage(parent.Handle, WM_SETREDRAW, true, 0); 
//parent.Refresh(); 
} 

任何人都可以請我建議任何解決方案,重新繪製子面板而不影響父母?

在此先感謝。

問候, Pannir

回答

-1

我不能複製的問題,孩子犯規觸發的OnPaint父。該消息框不是觸發重新繪製它,或按鈕,如果它在面板上按?

+0

考慮向OP,而不是評論的答案 – jolySoft

+0

@tim形式的其他問題,只需複製粘貼第一代碼片段到應用程序並運行。當點擊「Invalidate Child」按鈕時,我已經使ChildPanel單獨失效。但是兩個面板都調用了OnPaint方法並顯示消息框。 – Selvamz

+0

當另一個表單(如消息框使其無效時)觸發面板onpaint。這不是一個需要回答的問題,這是一個事實。使子控件失效不會觸發父對象的另一個事實。如果一個按鈕在父面板上,那麼按下它將會使它所在的面板無效,這是另一個事實。請不要濫用或光顧我,重新閱讀我說的話。 – tim

相關問題