今天我遇到了以下问题,我想知道是否有解决方案。
我的想法是构建匿名类并将其作为WinForm BindingSource的数据源:
public void Init()
{
var option1 = new
{
Id = TemplateAction.Update,
Option = "Update the Templates",
Description = "Bla bla 1."
};
var option2 = new
{
Id = TemplateAction.Download,
Option = "Download the Templates",
Description = "Bla bla 2."
};
var list = new[] {option1, option2}.ToList();
bsOptions.DataSource = list; // my BindingSource
// cboTemplates is a ComboBox
cboTemplates.DataSource = bsOptions;
cboTemplates.ValueMember = "Id";
cboTemplates.DisplayMember = "Option";
lblInfoTemplates.DataBindings.Add("Text", bsOptions, "Description");
}
到目前为止,这很好用。
我遇到的问题是从BindingSource的“Current”属性中获取Id,因为我无法将其转换回匿名类型:
private void cmdOK_Click(object sender, EventArgs e)
{
var option = (???)bsOptions.Current;
}
我想猜测找不到“Current”的类型并访问“Id”属性的方法吗?也许有人有好的解决方案...
我知道还有其他(更好的)方法来获取Id(反射,从ComboBox读取值,不使用匿名类型等),我只是好奇是否可能以一种简洁的方式从bsOptions.Current中获取类型。