【问题标题】:Collection of comboBoxes in WinFormsWinForms 中组合框的集合
【发布时间】:2016-01-29 20:27:33
【问题描述】:

我正在开发小型 winforms 应用程序。我的一个表单包含几个组合框:

由于我试图在我的项目中使用 MVP 模式,所以我决定为该表单创建 View 和 Presenter。通过适当的接口进行通信。

ComboBox 可以用它的 DataSource(即列出 os 字符串)和 SelectedIndex 来完全描述(根据我的需要)。这就是我创建正确界面的原因:

public interface IMyView
{
    MyViewPresenter { set; }

    IEnumerable<string> ComboBox1stDataSource { get; set; }
    int ComboBox1SelectedIndex { get; set; }

    IEnumerable<string> ComboBox2ndDataSource { get; set; }
    int ComboBox2ndSelectedIndex { get; set; }
    //for third comboBox it will be the same
}

我在 View 类中实现了该接口:

public partial class MaterialDatabasePropertiesForm : Form, IMaterialDatabasePropertiesView, IMyView
{

    public MaterialDatabasePropertiesPresenter Presenter { private get; set; }

    public IEnumerable<string> ComboBox1stDataSource
    {
        get { return comboBox1st.DataSource as List<string>; }
        set { comboBox1st.DataSource = value; }
    }
    public int ComboBox1SelectedIndex
    {
        get { return comboBox1st.SelectedIndex; }
        set { comboBox1st.SelectedIndex = value; }
    }

    public IEnumerable<string> ComboBox2ndDataSource
    {
        get { return comboBox2nd.DataSource as List<string>; }
        set { comboBox2nd.DataSource = value; }
    }
    public int ComboBox2ndSelectedIndex
    {
        get { return comboBox2nd.SelectedIndex; }
        set { comboBox2nd.SelectedIndex = value; }
    }
}

当一切都像上面那样设置时,我使用在我的 Presenter 中的接口中声明的属性来更改表单中组合框的属性。

虽然这似乎是一个很好的解决方案,但对我来说还不够。在我的原始应用程序中,我有 14 个组合框,将来这个数字可能会改变。

我想要让它更有弹性。我正在考虑在视图中创建一些组合框集合,但我无法弄清楚。

我的示例解决方案很糟糕,因为它甚至无法编译:

private List<List<string>> collectionOfComboBoxesDataSources = new List<List<string>>()
        {
            ref comboBox1st.DataSource,         //  I get error:
            ref comboBox2nd.DataSource,         //  "Cannot acces non-static field
            ref comboBox3rd.DataSource          //   <comboBoxName> in static context"
        };

    //this property would be part of IMyView
    public List<List<string>> CollectionOfComboBoxesDataSources
    {
        get { return collectionOfComboBoxesDataSources; }
        set { collectionOfComboBoxesDataSources = value; }
    }

我可以做些什么来创建集合(或类似的东西)来访问我的组合框属性?

【问题讨论】:

    标签: c# winforms combobox user-controls


    【解决方案1】:

    您可以尝试遍历您的表单。

    List<ComboBox> listOfCombobox = new List<ComboBox>();
    
    foreach(var combobox in this.controls.OfType<ComboBox>())
    {
           listOfCombobox.Add(combobox);
    }
    

    如果您尝试这样做。 然后您可以通过索引访问列表,因此您可以访问每个组合框的属性。

    【讨论】:

    • 这可能会有所帮助,但如果我想创建一组以上的组合框怎么办?
    • 您可以在面板上进行分组。然后迭代每个面板,这样你就可以获得“组”。不是最好的方法,但它会起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 2012-02-15
    相关资源
    最近更新 更多