2011-11-20 111 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... 
    } 
} 
相关问题