0

我目前正在尝试在 Windows 窗体中构建一个 DataGridView,以向用户显示他们可以打开和关闭的设置列表。DatGridView 将有两列,第一列将描述设置,第二列将包含一个复选框,允许用户打开或关闭设置。因此,例如 DataGridView 看起来像:

| Descriptions        |   Set   |
---------------------------------
| Description 1       |  true   |
| Description 2       |  false  |
| Description 3       |  false  |
...

在我的项目设置中,我目前有一个布尔值列表,Pref1,Pref2,Pref3 等,我想将其绑定到 DataGridView 中的复选框,以便可以自动操作它们,而无需我在单元格值时进行任何手动检查已被编辑,因此我可以保存应用程序不同实例之间的更改。

我尝试搜索一些解决方案并遇到以下问题并将其添加到表单构造函数中:

// Build preference dictionary
Dictionary<String, bool> Preferences = new Dictionary<String, bool>();
preferences.Add("Description 1", Settings.Default.Pref1);
preferences.Add("Description 2", Settings.Default.Pref2);
....

// Copy dictionary to list
List<KeyValuePair<String, bool>> PreferenceList = new List<KeyValuePair<String, bool>>();
foreach (KeyValuePair<String, bool> item in Preferences)
    PreferenceList.Add(item);

// Set the GridView DataSource and values displayed in each column
GridView.AutoGenerateColuns = false;
GridView.DataSource = new BindingList<KeyValuePair<String, bool>>(PreferenceList);
GridView.Columns[0].DataPropertyName = "Key";
GridView.Columns[1].DataPropertyName = "Value";

当表单加载时,DataGridView 会按预期填充,但无法操作第二列中的 CheckBox。经过一些调试后,我注意到当我将 DataPropertyName 设置为“Value”时,第二列变为 ReadOnly,并且我无法在不引发异常的情况下更改此 ReadOnly 设置。

有没有办法解决这个只读问题?我还阅读并考虑过创建自己的 Preference 类,如下所示:

public Class Preference
{
    public String Description  { get, set }
    public bool Selected  { get, set }
}

然后创建这些首选项的数组,将每个首选项的“选定”属性绑定到我的设置类中的一个布尔值,然后将首选项数组设置为 DataGridViews 数据源。这是一个可行的解决方案,还是可能有另一种我没有考虑/意识到的替代方案?

对不起,我只是想尝试解释一切,所以我问的内容不会混淆:)

提前致谢。

4

1 回答 1

2
GridView.DataSource = Preferences 
   .Select(p => new Preference {Description = p.Key, Selected = p.Value})
   .ToList();
GridView.Columns[0].DataPropertyName = "Description";
GridView.Columns[1].DataPropertyName = "Selected";
于 2011-04-21T08:45:21.963 回答