开发者

Programmatically Binding DataGrid to List array

开发者 https://www.devze.com 2023-03-24 04:04 出处:网络
I have to List of Data : List<string[]> dataRow = new List<string[]>(); every string[] array are full with 30 data for each row.

I have to List of Data :

List<string[]> dataRow = new List<string[]>();
  1. every string[] array are full with 30 data for each row.
  2. Column Name are already exists.

I'm trying to display it like this :

XAML :

<DataGrid Margin="8,259,8,8" IsReadOnly="True" AutoGenerateColumns="False" AlternatingRowBackground="Gainsboro"  AlternationCount="2" Name="MyDataGrid" />

C# :

MyDataGrid.ItemsSource = dataRow;

foreach( string[] cellContent in dataRow )
{
  foreach( string text in cellContent )
  {
    var column = new DataGridTextColumn
    {
      Binding = new Binding(text)
    };
    MyDataGrid.Columns.Add(column);
   }
 }

but i got a "ContextSwitchDeadlock" Error. How can i solve this?

Thank u for Helping

EDIT : solved but not with the databinding Way

I solved it like this :

List<string> ColumnName = new List<string>();
List<string[]> dataRow = new List<string[]>();
DataTable myTabl开发者_Go百科e = new DataTable();

 // Fill Array ColumnName and dataRow Here

foreach (string text in ColumnName)
{
   myTable.Columns.Add(text);
}
foreach (string[] cellContent in dataRow)
{
   myTable.Rows.Add(cellContent);
}
DatensatzGrid.ItemsSource = myTable.AsDataView();

Thank u for all the reply!!


The DataGrid control doesn't support Binding to 2D arrays, List<List..>> etc.

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

I created a subclassed DataGrid (DataGrid2D) to achieve this a while back.

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="MyDataGrid"
                 ItemsSource2D="{Binding DataRow}"/>

Since dataRow is a field a not a property binding won't work, but just setting the ItemsSource2D in code behind will be enough to display it

MyDataGrid.ItemsSource2D = dataRow;
  • DataGrid2D Library
  • DataGrid2D Source
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号