c# - 将字典与列表绑定(bind)的优雅方式

标签 c# winforms

除此之外再拆开,有没有简单的方法:

var dict = new Dictionary<string, List<string>>();

然后绑定(bind)到 winforms 的 gridview 控件中?

最佳答案

这不是 GridView,但是分组的 ListView 给出了相当好的结果:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;

namespace so
{
    public class Program
    {
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }

    public class Form1 : Form
    {
        ListView lv;

        public Form1()
        {
            lv = new ListView 
                 { 
                    Parent = this, 
                    Dock = DockStyle.Fill, 
                    ShowGroups = true, 
                    View = View.Details
                 };
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var dic = new Dictionary<string, List<string>>()
            {
                { "group 1", new[] { "sorry", "for having voted", "close for duplicate", "too fast" }.ToList() },
                { "group 2", new[] { "this is not", "a gridview", "but the result", "looks like" }.ToList() },
                { "group 3", new[] { "what you", "are trying", "to achieve" }.ToList() },
                { "group 4", new[] { "hope", "it", "helps" }.ToList() }
            };

            lv.BeginUpdate();

            lv.Columns.Clear();
            lv.Columns.Add("Text");

            lv.Groups.Clear();
            lv.Groups.AddRange(
                dic.Keys.Select(
                    s => new ListViewGroup(s, s)).ToArray());

            lv.Items.Clear();
            lv.Items.AddRange(
                dic.SelectMany(kv => 
                    kv.Value.Select(item => 
                        new ListViewItem
                            { 
                                Text = item,
                                Group = lv.Groups[kv.Key]
                            })).ToArray());

            lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);

            lv.EndUpdate();
        }
    }
}

关于c# - 将字典与列表绑定(bind)的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24270705/

相关文章:

c# - 将热键/快捷方式文本放在winforms中的工具条菜单项旁边

c# - 跟踪列数据更改以供高级分析师审查

c# - 在 asp.net core 中将字典发布到 web api

c# - .NET Core/EF Core 2.0 升级后急切加载 "No coercion operator is defined between types"

c# - 正确处理 lambda 表达式中可能出现的 System.NullReferenceException

c# - 避免 datagridview 的按钮点击/控件;自动显示

c# - 将 DataGridView Column 更改为 DataGridViewComboBoxColumn 入站 DataGridView

c# - 在没有 Linq 的情况下使用字符串对 List<T> 进行排序

c# - WPF/MVVM 在运行时加载 UserControl

c# - 获取嵌套对象的属性