如何调整绑定到List <t>的DataGrid列,而不是DataSet?</t>

时间:2009-04-21 06:30:57

标签: data-binding windows-mobile compact-framework

我正在尝试在基于Compact Framework 3.5 Window Mobile Professional 6 SDK的项目中使用System.Windows.Forms.DataGrid控件,通过将Something绑定到DataGrid来显示List<SomethingWrapper>类型对象的某些属性这样的public class SomethingWrapper { private Something data; public SomethingWrapper(Something data) { this.data = data; } public string Column1 { get { /* string from this.data */ } } public string Column2 { get { /* string from this.data */ } } } public class SomethingList : List<SomethingWrapper> { public SomethingList(IEnumerable<Something> items) { foreach (var item in items) Add(new SomethingWrapper(item)); Sort((a, b) => a.Column2.CompareTo(b.Column2); } } /* ... */ IEnumerable<Something> dataToShow = /* assume this is filled correctly */ SomethingDataGrid.DataSource = new SomethingList(dataToShow); 个实例:

Column1

这似乎工作正常:正确的数据显示在网格中,有两列名为Column2TableStyle,并在第二列上排序。我希望这是对这些数据的只读视图,所以一切都很好。

但是,我想设置列宽,似乎无法让它工作......

尝试明显:创建TableStyle,为每列创建文本框列样式实例,将其添加到SomethingDataGrid.TableStyle并将MappingName设置为生成的表格样式。 (这是来自内存,或者我也会显示我正在使用的确切代码。如果需要,我可以在今天晚些时候的某个地方添加该问题。)

然而,没有任何改变。我怀疑这与TableStyle对象上的DataSet有关;我昨天晚上找到的所有例子似乎都是将DataGrid数据绑定到MappingName并将DataSet设置为TableStyle.MappingName中的正确表名。否则,表格样式将无法达到预期效果,这就是我所看到的行为。

问题:我是否正在寻找解决问题的正确位置,如果是这样,在绑定到List<T>以显示{{T的属性时,我需要将{{1}}设置为什么? 1}} ...

(试图检查可能的重复项,但无法找到确切的匹配。如果我在那里发现错误,请纠正我。)

2 个答案:

答案 0 :(得分:2)

啊,毕竟看起来不太好:duplicate question found。将尝试从BindingList<T>派生和/或使用绑定源,以便我可以开始调用BindingSource.GetListName(null)来获取MappingName。希望这会有所帮助。如果没有,我会回来的......

答案 1 :(得分:1)

您可以通过创建DataGridTableStyle

来完成此操作

这是我使用的扩展方法:

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;

        foreach (var style in column)
        {
            ts.GridColumnStyles.AddColumn(style.Header, style.Column, style.Width);
        }

        ctrl.TableStyles.Clear();
        ctrl.TableStyles.Add(ts);
    }

然后我称之为:

    var newList = queriableData.ToList();
    ProductEdit.DataSource = newList;
    ProductEdit.SetColumnStyles(newList, new[]
                                      {
                                          new ColumnStyle("Name", 200),
                                          new ColumnStyle("Manufacturer", 100),
                                          new ColumnStyle("Size", 20)
                                      });

其中newList是对象的通用列表。