将动态创建的属性绑定到网格 [英] Bind dynamically created properties to a grid

查看:61
本文介绍了将动态创建的属性绑定到网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课是这样的,

My class is like this,

public class Person : DynamicObject
{
    public string Name { get; set; }
    public string Address { get; set; }
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();
    public int Count
    {
        get
        {
            return dictionary.Count;
        }
    }
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        string name = binder.Name;
        return dictionary.TryGetValue(name, out result);
    }
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }
    public void AddProperty<TTValue>(string key, TTValue value = default(TTValue))
    {
        dictionary[key] = value;
    }
    public void AddProperty(string typeName, string key, object value = null)
    {
        Type type = Type.GetType(typeName);
        dictionary[key] = Convert.ChangeType(value, type);
    }
}



然后我要从此类创建对象并将其添加到列表中



Then I''m creating objects from this class and add it to a list

dynamic p = new Person();
p.Name = "john&";
p.Address = "address"";
p.AddProperty<datetime>("BirthDate", DateTime.Now);

List<person> lstPerson=new List<person>();

lstPerson.Add(p);</person></person></datetime>




在添加了这样的几个人对象之后,我使用绑定源将其绑定到数据网格视图.但是绑定到网格视图后,我的动态创建的属性将不会显示在网格中.




After add few person objects like this I bind this to a datagrid view using a binding source. But after bound to the grid view my dynamically created properties are not shown in the grid.

推荐答案

您的类需要实现ICustomTypeDescriptor接口.当需要知道类型的属性时,框架会查询此接口.不久前,我写了一篇关于非常相似主题的文章.实际上,我也使用了Person类.就我而言,我正在创建基线属性,例如Address1,Address2等.任何类的无限基线 [ ^ ]

但是,为简单起见,您可以选择一条仍然可行的简单得多的道路.使您的Person类继承自DataTable并在其中包含一个DataRow.添加自定义属性时添加列.
Your class needs to implement the ICustomTypeDescriptor interface. The framework queries this interface when it needs to know what are the properties of your type. I wrote an article on a very similar subject a while ago. In fact, I used a Person class as well. In my case, I was creating baseline properties, such as Address1, Address2, etc. Unlimited baselines for any class[^]

However, for simplicity, you may choose a much simpler road that may still work. Make your Person class inherit from DataTable and have a single DataRow in it. Add columns when you add custom properties.


这篇关于将动态创建的属性绑定到网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆