我知道如何使用构造函数将对象从父窗体传递到子窗体。
例如,在父表单中,我这样做:
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);
}
}
我仍然试图搞定属性......如何使用属性而不是重载构造函数来执行此操作?
答案 0 :(得分: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以使用accounts属性:
// populate comboBox with accounts
private void PopulateComboBox()
{
foreach (BankAccount b in this.accounts)
{
comboBoxAccount.Items.Add(b);
}
}
答案 1 :(得分:0)
在WithdrawDialog中执行:
public WithdrawDialog()
{
InitializeComponent();
}
public BankAccountCollection Accounts{
set{
PopulateComboBox(value);
}
}
调用表单中的执行:
WithdrawDialog dlg = new WithdrawDialog{Accounts=cust.Accounts};
(这个花括号调用Object Initializer)
答案 2 :(得分: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);
}
}
}
答案 3 :(得分:0)
虽然可以使用公共财产来执行此操作,但不建议这样做。方法更适合这种情况,因为您需要执行逻辑来填充控件。
如果您只是想从构造函数中删除它,请将PopulateComboBox设置为public或internal(如果父项和子项位于同一个程序集中),并考虑将名称更改为更具描述性的名称,例如“PopulateBankAccounts”或“AddBankAccounts”。
然后您可以在父表单中执行以下操作:
using (WithdrawDialog dlg = new WithdrawDialog())
{
dlg.AddBankAccounts(cust.Accounts)
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.Ok)
{
//etc...
}
}