gpt4 book ai didi

wpf - 字典绑定(bind)到 ListView WPF

转载 作者:行者123 更新时间:2023-12-02 07:53:21 27 4
gpt4 key购买 nike

我有一个包含字典项目的列表。这意味着

List[0] = Dictionary Item => Item[0] = id,Item[1] = 名称,Item[2] = 金额。

我需要以网格的方式在 ListView 控件中显示它。字典可能会有所不同。

更新:

列表中的每个项目如下所示:

["_id"] = "11212131"["标题"] = "这是标题"["DateCreated"] = "某个日期"

字典中的项目可以不同。

更新 2:

我正在使用以下代码创建一个动态 Gridview 控件,然后将列添加到 GridView 控件中。它可以工作,但现在有一条长长的水平线,由相同的重复列组成。我需要显示列名以及属于该列的数据。

  var gridview = new GridView();

foreach (var o in objs)
{
var dic = o as Dictionary<String, Object>;
var enumerator = dic.GetEnumerator();
while (enumerator.MoveNext())
{
var current = enumerator.Current;
var gridViewColumn = new GridViewColumn();
gridViewColumn.Header = current.Key;
var binding = new Binding(current.Key);
//binding.Source = current;

gridViewColumn.DisplayMemberBinding = binding;

gridview.Columns.Add(gridViewColumn);

}

// new row

}

lvCollections.View = gridview;

更新 3:

我很接近。它可以工作,但它只显示一个带有重复列的长单行。

 var gridview = new GridView();


foreach (var o in objs)
{

var dic = o as Dictionary<String, Object>;
var enumerator = dic.GetEnumerator();
while (enumerator.MoveNext())
{var gridViewColumn = new GridViewColumn();
var current = enumerator.Current;
gridViewColumn.Header = current.Key;
var binding = new Binding();
binding.Source = current;
binding.Path = new PropertyPath("Value");

gridViewColumn.DisplayMemberBinding = binding;
gridview.Columns.Add(gridViewColumn);

}


// new row

}

lvCollections.ItemsSource = objs;
lvCollections.View = gridview;

最佳答案

像这样生成您的 GridView 列:

public void OnDataContextChanged(...)
{
var distinctKeys = (
from dict in (List<Dictionary<string,object>>)DataContext
from key in dict.Keys
select key
).Distinct();

gridView.Columns.ReplaceWith(
from key in distinctKeys
orderby key
select new GridViewColumn
{
Header = key,
DisplayMemberBinding = new Binding("[" + key + "]"),
});
}

// The above code uses an extension method like this
static void ReplaceWith<T>(this ObserableCollection<T> collection, IEnumerable<T> newItems)
{
collection.Clear();
foreach(var item in newItems)
collection.Add(item);
}

除非您的字典键包含特殊字符,否则这将起作用。完成这项工作的关键是绑定(bind)路径中的索引器语法('[' 和 ']')。

关于wpf - 字典绑定(bind)到 ListView WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2375281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com