[英]How can I change the FontFamily Property in all Controls in Windows Forms Application?
[英]How can I change the properties of controls in all tabs in Windows Forms Application?
我一直在尋找這個答案有一段時間沒有運氣。 看來這是一個相當簡單的問題,但我什么都沒想,所以去:
我想將所有選項卡中的所有控件都設置為ReadOnly = true或Enabled = false(或相反)。
我正在使用此代碼:
public void readOnly(bool read)
{
if (read == true)
{
foreach (var c in mainTab.Controls)
{
if (c is TextBox)
{
((TextBox)c).ReadOnly = true;
}
if (c is CheckBox)
{
((CheckBox)c).Enabled = false;
}
Etc. ......
如何在不重復代碼的情況下將更改應用於所有選項卡,而不僅是mainTab? 我是編程新手,所以如果我遺漏了一些明顯的東西,我深表歉意...
如果已經回答了這個問題,您能否將我指向該頁面?
要訪問所有選項卡,可以使用TabControl
的TabPages
屬性。 此外,您可以大大簡化代碼:
public void SetReadOnly(bool readOnly)
{
foreach (TabPage tab in tabControl.TabPages)
{
foreach (Control c in tab.Controls)
{
if (c is TextBox)
{
((TextBox)c).ReadOnly = readOnly;
}
else
{
// All controls support this property
c.Enabled = !readOnly;
}
}
}
}
您可以創建一個方法,該方法將在選項卡控件中的每個選項卡頁的控件之間循環,並設置控件的Enabled
屬性,並具有一個布爾型參數來說明該值應為:
private void SetTabControlEnabled(bool enabled)
{
foreach (TabPage tabPage in tabControl1.TabPages)
{
foreach (Control control in tabPage.Controls)
{
control.Enabled = enabled;
}
}
}
然后,作為示例,您可以調用此方法並傳遞true
以啟用控件,或者傳遞false
以禁用控件:
private void btnEnable_Click(object sender, EventArgs e)
{
SetTabControlEnabled(true);
}
private void btnDisable_Click(object sender, EventArgs e)
{
SetTabControlEnabled(false);
}
您需要一個遞歸函數:
public static void EnabledDisabeldControls(System.Windows.Forms.Control.ControlCollection paramControls, bool enabled)
{
foreach (System.Windows.Forms.Control c in paramControls)
{
if (c is TextBox)
{
((TextBox)c).ReadOnly = !enabled;
}
if (c is CheckBox)
{
((CheckBox)c).Enabled = enabled;
}
EnabledDisabeldControls(c.Controls, enabled);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.