【问题标题】:Two way binding between DataGrid and an arrayDataGrid 和数组之间的两种方式绑定
【发布时间】:2011-07-18 17:47:20
【问题描述】:

我有一个数组叫做:

string[,] TableData;

我可以使用绑定将其内容与 DataGrid 控件链接吗?

如果可能,我希望用户能够编辑网格并反映数组中的更改。

【问题讨论】:

    标签: c# wpf arrays datagrid


    【解决方案1】:

    看到这个问题:How to populate a WPF grid based on a 2-dimensional array

    您可以使用this control 称为DataGrid2D (source code here)。要使用它,只需添加对 DataGrid2DLibrary.dll 的引用,添加此命名空间

    xmlns:dg2d="clr-namespace:DataGrid2DLibrary;assembly=DataGrid2DLibrary"
    

    然后创建一个 DataGrid2D 并将其绑定到您的 IList、2D 数组或 1D 数组,像这样

    <dg2d:DataGrid2D Name="dataGrid2D"
                     ItemsSource2D="{Binding Int2DList}"/>
    

    用户将能够编辑数据,在DataGrid 中所做的更改将反映在二维数组中

    【讨论】:

    • @Thanks Meleak,我一直在阅读这篇文章,但我对用 2D 数组而不是组件网格填充 DataGrid 很感兴趣。
    • @Jaime Oro:更新了我的答案。我在之前的项目中有同样的需求,创建了一个子类DataGrid,你可以试试
    • 完美运行!谢谢天才!
    【解决方案2】:

    您不能将矩阵绑定到DataGrid。但是,根据您要实现的目标,您可以将其转换为 class 的数组。

    你的矩阵的内容是什么?你为什么不试试这样的东西?

    public class MyClass
    {
        public string A { get; set; }
        public string B { get; set; }
    
        public MyClass(string a, string b)
        {
            Debug.Assert(a != null);
            Debug.Assert(b != null);
    
            this.A = a;
            this.B = b;
        }
    }
    

    然后实例化如下:

    MyClass[] source = { new MyClass("A", "B"), new MyClass("C", "D") };
    this.dataGrid.ItemsSource = source;
    

    或者,如果您无法修改源的类型,请尝试使用 LINQ 进行投影:

    var source = (from i in Enumerable.Range(0, matrix.GetLength(0))
                  select new MyClass(matrix[i, 0], matrix[i, 1])).ToList();
    this.dataGrid1.ItemsSource = source;
    

    【讨论】:

    • 这里的问题是我的矩阵可以有任意数量的列/行。
    • 这对我来说效果很好 - 我有固定数量的列。我使用了索引器,因此可以将其作为数组或数据绑定 List. 访问
    • 这仅适用于您具有静态列数和行数
    【解决方案3】:

    最简单的方法应该是使用 WPF Datagrid 中的构建并将您的 Array 投影到将被绑定的 View 类。

    您希望您的用户能够添加行吗?如果是,则无法绑定到数组,因为您无法添加行。

    如果您有任意数量的列,您应该能够将数组投影到动态对象并将数据网格的 AutoGenerateColumns 属性设置为 true。你的列有名字吗?

    【讨论】:

    • 我希望用户能够添加行和列。列没有名字。
    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2015-08-09
    • 2011-03-06
    • 2020-07-12
    • 2017-08-06
    相关资源
    最近更新 更多