我正在开发小型winforms app。我的一个表单包含很少的组合框:
当我尝试在我的项目中使用MVP模式时,我决定为该表单创建View和Presenter。通过适当的界面进行沟通。
ComboBox可以用其DataSource(即list os strings)和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中的Interface中声明的属性来更改表单中的组合框的属性。
虽然它似乎是一个很好的解决方案,但对我来说还不够。在我的原始应用程序中,我有14个组合框,这个数字将来可能会改变。
我想要的是让它更有弹性。我在考虑创建一些comboBox的集合,但我无法弄明白。
我的样本解决方案很糟糕,因为它甚至无法编译:
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; }
}
如何创建集合(或类似的东西)以访问我的组合框属性?
答案 0 :(得分:1)
You could try to iterate through your form.
List<ComboBox> listOfCombobox = new List<ComboBox>();
foreach(var combobox in this.controls.OfType<ComboBox>())
{
listOfCombobox.Add(combobox);
}
If you're trying to do this. Then you can access the list via index, so you can access your properties of each combobox.