数据绑定动态数据 [英] Data binding dynamic data

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

问题描述

我有一组'动态数据',我需要绑定到GridControl。到目前为止,我一直使用System.Data命名空间的标准DataTable类。这已经很好,但是我被告知我不能使用这个,因为它在客户端和网络之间的网络序列化太重了。服务器。



所以我以为我可以轻松地复制一个切割版本的DataTable类,只需要一个类型列表<字典< ; string,object>> 其中List表示行的集合,每个Dictionary表示一列,列名和值作为KeyValuePair类型。我可以设置网格以使DataField列与Dictionary中的键匹配(就像我在为DataTable的列名所做的那样)。



  gridControl.DataSource = table; 
gridControl.RefreshDataSource();

网格没有数据...



我想我需要实现 IEnumerator - 对此的任何帮助将不胜感激!



示例调用代码如下所示:

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

var row = new Dictionary&字符串,对象>
{
{Field1,Data1},
{Field2,Data2},
{Field3,Data3
};

table.Add(row);

gridControl1.DataSource = table;
gridControl1.RefreshDataSource();


解决方案

欢迎来到S的美好世界ystem.ComponentModel。 .NET的这个黑暗角落非常强大,但非常复杂。



谨慎的一句话;除非你有很多时间,否则你可能会很好地简单地将其以任何你喜欢的机制序列化,但是在每一端将其再次回收成一个 DataTable 。 ..以下是不是为了微弱的; -p



首先 - 数据绑定(表)适用于列表 IList / IListSource ) - 所以列表< T> 应该是(编辑:我误读某事)。但是不明白你的字典实际上是列...



要获得一个类型,假装有列需要使用自定义 PropertyDescriptor 实现。有几种方法可以执行此操作,具体取决于列定义是否始终相同(但在运行时确定,即可能来自config),或者是否根据用法进行更改(如每个 DataTable 实例可以有不同的列)



对于每个实例定制,您需要查看 ITypedList - 这个野兽(在添加中实现 )具有呈现表格数据的属性的有趣任务...但它不是单独:



对于每类型定制,您可以查看 TypeDescriptionProvider - 这可以建议一个class ...



...或者您可以实现 ICustomTypeDescriptor - 但这仅用于(列表)在非常的情况下(对象索引器( public object this [int index] {get;} )和列表中至少有一行在绑定的时候)(当这个界面更加有用的时候)绑定谨慎的对象 - 即不是列表)。



实现 ITypedList ,并提供一个 PropertyDescriptor 模型是艰苦的工作...因此它只是偶尔完成。我很熟悉它,但我不会这样做只是为了笑...






这是一个非常简单的实现(所有列都是字符串;没有通知(通过描述符),没有验证( IDataErrorInfo ),没有转换( TypeConverter ),没有额外的列表支持( IBindingList / IBindingListView ), ( IListSource ),没有其他元数据/属性等):

 使用System.ComponentModel; 
使用System.Collections.Generic;
使用系统;
使用System.Windows.Forms;

静态类程序
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
PropertyBagList list = new PropertyBagList();
list.Columns.Add(Foo);
list.Columns.Add(Bar);
list.Add(abc,def);
list.Add(ghi,jkl);
list.Add(mno,pqr);

Application.Run(new Form {
Controls = {
new DataGridView {
Dock = DockStyle.Fill,
DataSource = list
}
}
});
}
}
class PropertyBagList:List< PropertyBag>,ITypedList
{
public PropertyBag Add(params string [] args)
{
if(args == null)throw new ArgumentNullException(args);
if(args.Length!= Columns.Count)throw new ArgumentException(args);
PropertyBag bag = new PropertyBag(); (int i = 0; i< args.Length; i ++)
{
bag [Columns [i]] = args [i];
}
Add(bag);
回包;
}
public PropertyBagList(){Columns = new List< string>(); }
public List< string>列{get;私人集合

PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor [] listAccessors)
{
if(listAccessors == null || listAccessors.Length == 0)
{
PropertyDescriptor [] props = new PropertyDescriptor [Columns.Count]; (int i = 0; i< props.Length; i ++)
{
props [i] = new PropertyBagPropertyDescriptor(Columns [i]);

}
return new PropertyDescriptorCollection(props,true);
}
抛出新NotImplementedException(关系未实现);
}

string ITypedList.GetListName(PropertyDescriptor [] listAccessors)
{
returnFoo;
}
}
class PropertyBagPropertyDescriptor:PropertyDescriptor
{
public PropertyBagPropertyDescriptor(string name):base(name,null){}
public override object GetValue (object component)
{
return((PropertyBag)component)[Name];
}
public override void SetValue(object component,object value)
{
((PropertyBag)component)[Name] =(string)value;
}
public override void ResetValue(object component)
{
((PropertyBag)component)[Name] = null;
}
public override bool CanResetValue(object component)
{
return true;
}
public override bool ShouldSerializeValue(object component)
{
return((PropertyBag)component)[Name]!= null;
}
public override类型PropertyType
{
get {return typeof(string); }
}
public override bool IsReadOnly
{
get {return false; }
}
public override Type ComponentType
{
get {return typeof(PropertyBag); }
}
}
class PropertyBag
{
private readonly Dictionary< string,string>值
=新词典< string,string>();
public string this [string key]
{
get
{
string value;
values.TryGetValue(key,out value);
返回值;
}
set
{
if(value == null)values.Remove(key);
else values [key] = value;
}
}
}


I have a set of 'dynamic data' that I need to bind to the GridControl. Up until now, I have been using the standard DataTable class that's part of the System.Data namespace. This has worked fine, but I've been told I cannot use this as it's too heavy for serialization across the network between client & server.

So I thought I could easy replicate a 'cut-down' version of the DataTable class by simply having a type of List<Dictionary<string, object>> whereby the List represents the collection of rows, and each Dictionary represents one row with the column names and values as a KeyValuePair type. I could set up the Grid to have the column DataField properties to match those of the keys in the Dictionary (just like I was doing for the DataTable's column names.

However after doing

gridControl.DataSource = table;
gridControl.RefreshDataSource();

The grid has no data...

I think I need to implement IEnumerator - any help on this would be much appreciated!

Example calling code looks like this:

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

var row = new Dictionary<string, object>
{
    {"Field1", "Data1"},
    {"Field2", "Data2"},
    {"Field3", "Data3"}
};

table.Add(row);

gridControl1.DataSource = table;
gridControl1.RefreshDataSource();

解决方案

Welcome to the wonderful world of System.ComponentModel. This dark corner of .NET is very powerful, but very complex.

A word of caution; unless you have a lot of time for this - you may do well to simply serialize it in whatever mechanism you are happy with, but rehydrate it back into a DataTable at each end... what follows is not for the faint-hearted ;-p

Firstly - data binding (for tables) works against lists (IList/IListSource) - so List<T> should be fine (edited: I misread something). But it isn't going to understand that your dictionary is actually columns...

To get a type to pretend to have columns you need to use custom PropertyDescriptor implementations. There are several ways to do this, depending on whether the column definitions are always the same (but determined at runtime, i.e. perhaps from config), or whether it changes per usage (like how each DataTable instance can have different columns).

For "per instance" customisation, you need to look at ITypedList - this beast (implemented in addition to IList) has the fun task of presenting properties for tabular data... but it isn't alone:

For "per type" customisation, you can look at TypeDescriptionProvider - this can suggest dynamic properties for a class...

...or you can implement ICustomTypeDescriptor - but this is only used (for lists) in very occasional circumstances (an object indexer (public object this[int index] {get;}") and at least one row in the list at the point of binding). (this interface is much more useful when binding discreet objects - i.e. not lists).

Implementing ITypedList, and providing a PropertyDescriptor model is hard work... hence it is only done very occasionally. I'm fairly familiar with it, but I wouldn't do it just for laughs...


Here's a very, very simplified implementation (all columns are strings; no notifications (via descriptor), no validation (IDataErrorInfo), no conversions (TypeConverter), no additional list support (IBindingList/IBindingListView), no abstraction (IListSource), no other other metadata/attributes, etc):

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

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        PropertyBagList list = new PropertyBagList();
        list.Columns.Add("Foo");
        list.Columns.Add("Bar");
        list.Add("abc", "def");
        list.Add("ghi", "jkl");
        list.Add("mno", "pqr");

        Application.Run(new Form {
            Controls = {
                new DataGridView {
                    Dock = DockStyle.Fill,
                    DataSource = list
                }
            }
        });
    }
}
class PropertyBagList : List<PropertyBag>, ITypedList
{
    public PropertyBag Add(params string[] args)
    {
        if (args == null) throw new ArgumentNullException("args");
        if (args.Length != Columns.Count) throw new ArgumentException("args");
        PropertyBag bag = new PropertyBag();
        for (int i = 0; i < args.Length; i++)
        {
            bag[Columns[i]] = args[i];
        }
        Add(bag);
        return bag;
    }
    public PropertyBagList() { Columns = new List<string>(); }
    public List<string> Columns { get; private set; }

    PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)
    {
        if(listAccessors == null || listAccessors.Length == 0)
        {
            PropertyDescriptor[] props = new PropertyDescriptor[Columns.Count];
            for(int i = 0 ; i < props.Length ; i++)
            {
                props[i] = new PropertyBagPropertyDescriptor(Columns[i]);
            }
            return new PropertyDescriptorCollection(props, true);            
        }
        throw new NotImplementedException("Relations not implemented");
    }

    string ITypedList.GetListName(PropertyDescriptor[] listAccessors)
    {
        return "Foo";
    }
}
class PropertyBagPropertyDescriptor : PropertyDescriptor
{
    public PropertyBagPropertyDescriptor(string name) : base(name, null) { }
    public override object GetValue(object component)
    {
        return ((PropertyBag)component)[Name];
    }
    public override void SetValue(object component, object value)
    {
        ((PropertyBag)component)[Name] = (string)value;
    }
    public override void ResetValue(object component)
    {
        ((PropertyBag)component)[Name] = null;
    }
    public override bool CanResetValue(object component)
    {
        return true;
    }
    public override bool ShouldSerializeValue(object component)
    {
        return ((PropertyBag)component)[Name] != null;
    }
    public override Type PropertyType
    {
        get { return typeof(string); }
    }
    public override bool IsReadOnly
    {
        get { return false; }
    }
    public override Type ComponentType
    {
        get { return typeof(PropertyBag); }
    }
}
class PropertyBag
{
    private readonly Dictionary<string, string> values
        = new Dictionary<string, string>();
    public string this[string key]
    {
        get
        {
            string value;
            values.TryGetValue(key, out value);
            return value;
        }
        set
        {
            if (value == null) values.Remove(key);
            else values[key] = value;
        }
    }
}

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

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