用于编辑Dictionary的C#GUI控件

maf*_*afu 2 c# user-controls dictionary

是否有标准控件允许用户编辑String to String Dictionary的键值对?

如果没有,你会如何实现?我有一些想法,但没有一个看起来很棒.

Mar*_*ell 7

不,没有一个内置.实现一个; 如何实现2列DataGridView,实现IDataErrorInfo重复键导致红色错误blob:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
class Pair : IDataErrorInfo
{
    internal IList<Pair> Parent { get; set; }
    public string Key { get; set; }
    public string Value { get; set; }

    string IDataErrorInfo.Error
    {
        get { return ""; }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {   
            if(columnName == "Key" && Parent != null && Parent.Any(
                x=> x.Key == this.Key && !ReferenceEquals(x,this)))
            {
                return "duplicate key";
            }
            return "";        
        }
    }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        BindingList<Pair> pairs = new BindingList<Pair>();
        // todo: fill from StringDictionary
        pairs.AddingNew += (s,a) =>
        {
            a.NewObject = new Pair { Parent = pairs };
        };
        Application.Run(new Form {
            Controls = {new DataGridView {
                Dock = DockStyle.Fill,
                DataSource = pairs
            }}
        });
    }
}
Run Code Online (Sandbox Code Playgroud)