从父组件向对话框传递数据

4

我在对话框表单中有一个下拉框,需要使用父表单的List<>填充该下拉框。由于无法通过对话框构造函数传递List<>,因此该如何实现呢?

frmChild frm = new frmChild();
frm.ShowDialog();
3个回答

7
您可以在表单上添加一个属性或方法,该属性或方法接受 List<items> 并将其填充到 ComboBox 中。
例如:
List<ItemType> items = GetItemsForFormsComboBox();
frmChild frm = new frmChild();
frm.SetComboItems(items);
frm.ShowDialog();

// in the form
public void SetComboItems(List<ItemType> items)
{
    foreach(var item in items)
    {
        myCombo.Add( /* construct combo item and use item to populate it here */ );
    }
}

1

你可以将对话框的属性设置成获取/设置List<> 数据。


0
你可以在表单上添加一个属性或方法,该属性或方法将接受List并填充ComboBox。
然后重载构造函数。
public class ComboBoxWindow : Window
{
    public ComboBoxWindow (Window origin)
    {
        // Now you can access your parent window's List<>.
    }

    // If necessary you can keep a reference to it.
    private Window _origin;
}

OR

public class ComboBoxWindow : Window
{   
    // If necessary you can keep a reference to it.
    private IList _items;

    public ComboBoxWindow (IList _items)
    {
        // Now you can access your list directly.
    }
}

两种方式都可以。

{享受}


第一种选择并不是世界上最好的想法,让一个子窗口“理解”其父窗口,如果您尝试在其他地方重复使用该窗口,那么这只会带来麻烦。第二个选项或者属性/方法无疑是更好的选择。 - Rob
你说得对,我的意思是使用第一种方法会增加额外的开销。尽管如此,我曾经使用第一种方法,在自定义窗口上设置了一个模糊效果,当窗口打开时,它表现得非常好。 - Micael Bergeron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接