Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way binding between DataGrid and an array

I have an an array called:

string[,] TableData;

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

If possible, I would like the user to be able to edit the Grid and reflect the changes in the array.

like image 515
Jaime Oro Avatar asked Mar 19 '11 12:03

Jaime Oro


3 Answers

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

like image 136
Fredrik Hedblad Avatar answered Nov 17 '22 02:11

Fredrik Hedblad


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;
like image 2
as-cii Avatar answered Nov 17 '22 02:11

as-cii


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?

like image 1
Zebi Avatar answered Nov 17 '22 02:11

Zebi