Map 2d array to DataGrid

I am trying to get a DataGrid to display content object[][]. This will be read-only, so I don't need notification changes or anything like that. Setting ItemSourceto object[][]simply displays the properties Arrayin the grid, and using it List<List<object>>instead does the same, which is clearly useless.

The number of columns in each 1d array can be arbitrary; I just want an unnamed column to be created for each element of the array in each row. How can i do this?

+3
source share
1 answer

See my answer in this question . This will also allow editing the values. Since you're just interested in displaying them, it might be easier to use a response from Jobi Joy if using a DataGrid is not a requirement.

Make a short version of the answer to this question. You will need the Ref class

public class Ref<T>
{  
    private readonly Func<T> getter;   
    private readonly Action<T> setter;  
    public Ref(Func<T> getter, Action<T> setter)   
    {   
        this.getter = getter;   
        this.setter = setter;   
    }  
    public T Value { get { return getter(); } set { setter(value); } }   
}  

And a helper class to get dynamic columns from a 2d array

public class BindingHelper
{
    public DataView GetBindable2DViewFromIList<T>(IList list2d)
    {
        DataTable dataTable = new DataTable();
        for (int i = 0; i < ((IList)list2d[0]).Count; i++)
        {
            dataTable.Columns.Add(i.ToString(), typeof(Ref<T>));
        }
        for (int i = 0; i < list2d.Count; i++)
        {
            DataRow dataRow = dataTable.NewRow();
            dataTable.Rows.Add(dataRow);
        }
        DataView dataView = new DataView(dataTable);
        for (int i = 0; i < list2d.Count; i++)
        {
            for (int j = 0; j < ((IList)list2d[i]).Count; j++)
            {
                int a = i;
                int b = j;
                Ref<T> refT = new Ref<T>(() => (list2d[a] as IList<T>)[b], z => { (list2d[a] as IList<T>)[b] = z; });                    
                dataView[i][j] = refT;
            }
        }
        return dataView;
    }
}

After that, you can use ItemsSource, like this

<DataGrid Name="dataGrid" 
          RowHeaderWidth="0" 
          ColumnHeaderHeight="0" 
          AutoGenerateColumns="True" 
          AutoGeneratingColumn="dataGrid_AutoGeneratingColumn"/> 

dataGrid.ItemsSource = BindingHelper.GetBindable2DViewFromIList<object>(m_2DArray);

private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
{ 
    DataGridTextColumn column = e.Column as DataGridTextColumn; 
    Binding binding = column.Binding as Binding; 
    binding.Path = new PropertyPath(binding.Path.Path + ".Value");
}
+1
source

Source: https://habr.com/ru/post/1780671/


All Articles