Two way binding between DataGrid and an array

后端 未结 3 2098
心在旅途
心在旅途 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 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;
    

提交回复
热议问题