Two way binding between DataGrid and an array

后端 未结 3 2084
心在旅途
心在旅途 2020-12-19 08:24

I have an an array called:

string[,] TableData;

Can I link its content with a DataGrid control using binding?

If possible, I would

相关标签:
3条回答
  • 2020-12-19 08:55

    See this question: How to populate a WPF grid based on a 2-dimensional array

    You can use this control called DataGrid2D (source code here). To use it just add a reference to DataGrid2DLibrary.dll, add this namespace

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

    and then create a DataGrid2D and bind it to your IList, 2D array or 1D array like this

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

    The users will be able to edit the data and changes made in the DataGrid will be reflected in the 2D Array

    0 讨论(0)
  • 2020-12-19 09:00

    The easiest way should be to use the build in WPF Datagrid and project your Array to a View class which will be bound.

    Do you want your users to be able to add rows? If yes binding to an array is not possible because you can't add rows.

    If you have any number of columns you should be able to project your array to a dynamic object and set the AutoGenerateColumns property of the datagrid to true. Do your columns have names?

    0 讨论(0)
  • 2020-12-19 09:12

    You can't bind a matrix to a DataGrid. However, depending on what you are trying to achieve, you could transform it to an array of class.

    What is the content of your matrix? Why don't you try something like this?

    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;
        }
    }
    

    Then instantiate something as follows:

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

    Alternatively, if you can't modify the type of your source, try to use LINQ to project it:

    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;
    
    0 讨论(0)
提交回复
热议问题