How to create a WPat Datagrid with an unknown number of columns

I need to collect and display a WPF data grid from a set of array of strings that I got from txt. The problem is that I do not know a priori what will be the number of columns, i.e. The number of elements in one array. So I defined in my xaml<DataGrid Grid.Row="2" ItemsSource="{Binding Path=Rows}" />

I tried to fill it in my view model, but I can’t just put my Observable Collection from the array as the source of the element, since only empty rows will be displayed in the datagrid.

I can also use a different approach in the Observable collection, since I create my array in the same method

this is my observable collection:

ObservableCollection<string[]> Rows = new ObservableCollection<string[]>;

in this method, I populate the collection

foreach(ListViewItem item in wsettings.lista)
        {                 
            TextBlock line = item.Content as TextBlock;
            string txt = line.Text;
            string[] x = txt.Split(stringSeparators, StringSplitOptions.None);               
            Rows.Add(x);
        }    

, . , ( ).

EDIT1:

EDIT2: ,

-1
2

DataTable class .Net. - , , (, .csv/Excel → DataTable + DataGrid wpf, DataTable + DataGridView WinForms).

DataTable (DataColumn) / , DataGrid (DataGridColumn) ( ), Name . DataTable .

note: DataGrid Columns ItemsSource. , .

note: DataGrid DataGridTextColumn. , AutoGeneratingColumn (. )

:

public class MyViewModel
{
    public DataTable Test { get; set; }
}

public MyWindow()
{
    InitializeComponent();
    var vm = new MyViewModel
                {
                    Test = new DataTable
                        {
                            Columns = {"A", "B", "C"}
                        }
                };            
    this.DataContext = vm;

}

XAML

<DataGrid AutoGenerateColumns="True"
          ItemsSource="{Binding Path=Test.DefaultView}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="#"/>
    </DataGrid.Columns>
</DataGrid>

( )

datagrid

+1

, . . :

public MainWindow()
{
    InitializeComponent();
    var viewModel = new ViewModel();
    var rows = viewModel.Rows;
    int numberOfColumns = rows[0].Length; //assume all string[] have the same length
    DataContext = new VM1();

    for (int i = 0; i < numberOfColumns; ++i)
    {
        dataGrid1.Columns.Add(new DataGridTextColumn() { Binding = new Binding("[" + i + "]"), Header = i.ToString() });
    }
    dataGrid1.ItemsSource = rows;
}
0

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


All Articles