【问题标题】:Dictionary of KeyValuePair as DataSourceKeyValuePair 字典作为数据源
【发布时间】:2014-03-25 16:50:07
【问题描述】:

如果得到以下对象:

Dictionary<int,KeyValuePair<int,string>> myData;

现在我想将此数据分配给 DataGrid。

将列的 DataPropertyName 设置为“Key”或“Value”可以正常工作(包含 Dictionary 的 Key (int) 和 Value (keyvaluepair)。

但我想在一列中显示 Pair 的键和值。

colWhatever.DataPropertyName="Value.Value" 似乎不起作用。

有没有办法做到这一点,还是我必须为此创建一个具有三个属性的类?

【问题讨论】:

  • 你在这里想要什么对我来说并不明显。内部字典中可能有任意数量的条目 - 您是否希望这些条目以某种方式显示在一个单元格中?
  • @Chris Ballard "colWhatever" 是一个列,而不是一个单元格

标签: c# winforms data-binding dictionary datagridview


【解决方案1】:

没有办法实现它。您可以使用 ViewModel 并绑定此视图模型的 List&lt;T&gt;,例如:

创建视图模型

public class DataViewModel
{
    public int Key { get; set; }
    public int ValueKey { get; set; }
    public string Value { get; set; }    
}

创建一个将Dictionary&lt;int,KeyValuePair&lt;int,string&gt;&gt; 转换为List&lt;DataViewModel&gt; 的方法:

public static List<DataViewModel> Convert(Dictionary<int,KeyValuePair<int,string>> dic)
{
    return dic.Select(item => new DataViewModel() { Key = item.Key, ValueKey = item.Value.Key, Value = item.Value.Value }).ToList();
}

并在DataSource 属性中应用此列表:

grid.DataSource = Convert(myData);

DataPropertyName 上应用 List 类型的属性。

grid.DataPropertyName = "Value";  

【讨论】:

  • 这就是我的意思“或者我必须为此创建一个具有三个属性的类”
  • 没办法实现,创建一个List是简单的方法。
  • +1 表示“没有办法实现它”。即使这不是我想听到的:)
  • 我同意,如果有一个支持按您发布的属性导航的网格可能会很好:Value.Property。也许用反射扩展网格可以工作哈哈
猜你喜欢
  • 1970-01-01
  • 2015-02-18
  • 2011-08-14
  • 2011-06-01
  • 1970-01-01
  • 2010-10-22
  • 2014-10-07
  • 1970-01-01
  • 2021-08-08
相关资源
最近更新 更多