2011-11-20 142 views
0

我知道如何使用構造函數將對象從父窗體傳遞到子窗體。通過屬性將對象從父窗體傳遞給子窗體(Winforms)

例如,在父窗體,我這樣做:

WithdrawDialog dlg = new WithdrawDialog(cust.Accounts); 

子窗體:

public WithdrawDialog(BankAccountCollection accounts) 
{ 
    InitializeComponent(); 
    PopulateComboBox(accounts); 
} 

// populate comboBox with accounts 
private void PopulateComboBox(BankAccountCollection accounts) 
{ 
    foreach (BankAccount b in accounts) 
    { 
     comboBoxAccount.Items.Add(b); 
    } 
} 

我還在試圖獲得屬性的竅門......我會怎麼使用屬性而不是重載的構造函數來做到這一點?

回答

3

在這裏你去:

WithdrawDialog dlg = new WithdrawDialog(); 
dlg.accounts = cust.Accounts; 
dlg.Show(); 

public WithdrawDialog() 
{ 
    InitializeComponent(); 
} 

private BankAccountCollection m_Accounts; 
public BankAccountCollection accounts { 
    get { 
     return m_Accounts; 
    } 
    set { 
     m_Accounts = value; 
     PopulateComboBox(m_Accounts); 
    } 
} 

// populate comboBox with accounts 
private void PopulateComboBox(BankAccountCollection accounts) 
{ 
    foreach (BankAccount b in accounts) 
    { 
     comboBoxAccount.Items.Add(b); 
    } 
} 

另外,PopupComboBox可以改寫使用帳戶屬性:

// populate comboBox with accounts 
private void PopulateComboBox() 
{ 
    foreach (BankAccount b in this.accounts) 
    { 
     comboBoxAccount.Items.Add(b); 
    } 
} 
0
在WithdrawDialog

做:

public WithdrawDialog() 
{ 
    InitializeComponent(); 
} 

public BankAccountCollection Accounts{ 
    set{ 
     PopulateComboBox(value); 
    } 
} 

在調用形式做:

WithdrawDialog dlg = new WithdrawDialog{Accounts=cust.Accounts}; 

(此花括號調用Object Initializer

0

在父窗體:

WithdrawDialog dlg = new WithdrawDialog(); 
dlg.Accounts = cust.Accounts; 

子窗體:

public class WithdrawDialog 
{ 
    private BankAccountCollection _accounts; 

    public WithdrawDialog() 
    { 
     InitializeComponent(); 
    } 

    public BankAccountCollection Accounts 
    { 
     get { return _accounts; } 
     set { _accounts = value; PopulateComboBox(_accounts); } 
    } 

    // populate comboBox with accounts 
    private void PopulateComboBox(BankAccountCollection accounts) 
    { 
     foreach (BankAccount b in accounts) 
     { 
      comboBoxAccount.Items.Add(b); 
     } 
    } 
} 
0

雖然可以用公共財產要做到這一點,它不會被推薦。一種方法更適合於此,因爲您需要執行邏輯來填充控件。

如果你只是想把它從你的構造函數中取出來,使PopulateComboBox爲public或internal(如果父類和子類在同一個程序集中),並考慮將名稱更改爲更具描述性的名稱,如「PopulateBankAccounts 「或」AddBankAccounts「。

然後,你可以做這樣的事情在父窗體:

using (WithdrawDialog dlg = new WithdrawDialog()) 
{ 
    dlg.AddBankAccounts(cust.Accounts) 
    DialogResult result = dlg.ShowDialog(); 

    if (result == DialogResult.Ok) 
    { 
     //etc... 
    } 
} 
相關問題