我正在使用最新版本的.NET Compact Framework构建一个小型VB应用程序。与我习惯的情况不同,数据网格控件有一些限制。我看到很多示例可以将网格的数据源绑定到数据集/数据表。是否可以绑定到通用列表?如果可以,该如何实现?
你可以将列表添加到数据源中,但接下来需要做更多的工作才能使列看起来符合你的要求。
实际上,我经常这样做,但稍微有点麻烦。请注意,我的示例正在使用.NET 3.5和一些C# 3.0功能,以使它更容易。
首先,这里是我正在使用的扩展方法:
public static T SelectedItem<T>(this DataGrid ctrl)
{
var cell = ctrl.CurrentCell;
var list = (IList<T>)ctrl.DataSource;
if (list == null)
return default(T);
if (list.Count == 0)
return default(T);
return list[cell.RowNumber];
}
private static void AddColumn(this GridColumnStylesCollection list, string header, string columnName, int width)
{
list.Add(
new DataGridTextBoxColumn
{
HeaderText = header,
MappingName = columnName,
Width = width
});
return;
}
public static void SetColumnStyles<T>(this DataGrid ctrl, T data, params ColumnStyle[] column) where T : class
{
var ts = new DataGridTableStyle();
ts.MappingName = data.GetType().Name;
for (int i = 0; i < column.Length; i++)
{
var style = column[i];
ts.GridColumnStyles.AddColumn(style.Header, style.Column, style.Width);
}
ctrl.TableStyles.Clear();
ctrl.TableStyles.Add(ts);
}
并且这个小类:
public class ColumnStyle
{
public string Header { get; private set; }
public string Column { get; private set; }
public int Width { get; private set; }
public ColumnStyle(string header, string column, int width)
{
Header = header;
Column = column;
Width = width;
}
public ColumnStyle(string column, int width)
{
Column = column;
Header = column;
Width = width;
}
}
public void LoadInventoryList(IList<InventoryItemSmall> list)
{
inventoryGrid.SuspendLayout();
inventoryGrid.DataSource = list;
inventoryGrid.SetColumnStyles(list, new[]
{
new ColumnStyle("Name", 170),
new ColumnStyle("Size", 30),
new ColumnStyle("Quantity", 30)
});
inventoryGrid.ResumeLayout();
}
我认为没有内置的方法可以将通用列表绑定到数据网格。但是,您可以相当容易地创建一个UserControl,该控件继承自datagrid,并覆盖/重载绑定方法以适应通用列表。基本方法是从通用列表生成DataTable,并将生成的DataTable绑定到基础datagrid。当然,这种方法是只读的。