2017-06-04 27 views
1

我想這個代碼在我的C#項目添加到每個按鈕:從每一個按鈕,在C#中刪除hover樣式

button1.FlatAppearance.MouseDownBackColor = button1.BackColor; 
button1.FlatAppearance.MouseOverBackColor = button1.BackColor; 
button1.FlatStyle = FlatStyle.Flat; 

我試過這個代碼在Form_Load事件,但該變種b保持空:

foreach (Control c in Controls) 
     { 
      Button b = c as Button; 
      if (b != null) 
      { 
       b.FlatAppearance.MouseOverBackColor = b.BackColor; 
       b.FlatAppearance.MouseDownBackColor = b.BackColor; 
       b.FlatStyle = FlatStyle.Flat; 
      } 
     } 

我該怎麼辦?

+0

你確定你的表單上有按鈕嗎?或者他們可能在另一個表格上?有關表單上控件的更多信息將會有所幫助。 – MetaColon

+0

這是一個wpf問題嗎? –

+0

@JoePhillips我不認爲你可以像這樣訪問WPF控件,所以我認爲它是關於WinForms的。 – MetaColon

回答

1

我只是假設這是關於WinForms。

由於當您的代碼似乎在按鈕直接在窗體上工作時,它們可能位於窗體上的另一個控件(容器)上。你現在可以搜索容器並檢查它們是否包含一個按鈕,但是當它們有容器時也會變得笨拙。因此,我建議使用遞歸:

private List<Control> GetAllControls(Control parent) 
{ 
    List<Control> controls = new List<Control>(); 
    controls.AddRange(parent.Controls.Cast<Control>()); //add all controls directly being on the current control 
    controls.AddRange(parent.Controls.Cast<Control>().SelectMany(GetAllControls)); //add all children from each control 
    return controls; 
} 

,你可以這樣調用:

foreach (Control c in GetAllControls(this)) 
{ 
    Button b = c as Button; 
    if (b != null) 
    { 
     b.FlatAppearance.MouseOverBackColor = b.BackColor; 
     b.FlatAppearance.MouseDownBackColor = b.BackColor; 
     b.FlatStyle = FlatStyle.Flat; 
    } 
} 

你可以閱讀更多關於遞歸here