【发布时间】:2015-12-24 02:12:31
【问题描述】:
所以我有这个Dictionary:
Dictionary<string, double> _statistics;
我想将这个 Dictionary 添加到我的 ListView 中,有 2 列:
DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Percent");
foreach (KeyValuePair<string, double> item in _statistics)
table.Rows.Add(item.Key, item.Value);
listView.ItemsSource = table;
得到一个错误:
无法将类型“System.Data.DataTable”隐式转换为 'System.Collections.IEnumerable'。存在显式转换(是 你错过了一个演员?)
编辑
我也试试这个:
public class MyItem
{
public string Name{ get; set; }
public double Percentage { get; set; }
}
var gridView = new GridView();
ipStatilistViewsticslistView.View = gridView;
gridView.Columns.Add(new GridViewColumn
{
Header = "Name",
DisplayMemberBinding = new Binding("Name")
});
gridView.Columns.Add(new GridViewColumn
{
Header = "Percent",
DisplayMemberBinding = new Binding("Percent")
});
foreach (KeyValuePair<string, double> item in _statistics)
listView.Items.Add(new MyItem { Name = item.Key, Percentage = item .Value});
在这种情况下,我只能看到我听到的 2 个专栏。
【问题讨论】:
-
为什么要使用
DataTable? -
我不在乎用什么,我只想用我的字典填充我的 ListView。
-
那么你可以写
listView.ItemsSource = _statistics。 ListView.ItemSource 将适用于任何实现IEnumerable接口的东西。 -
效果很好,我可以在 [] 大括号内看到我的值,而且我还需要列标题、宽度...