WPF DataGrid 动态列绑定

WPF DataGrid 动态列绑定

代码:


    



public partial class MainWindow : Window
{
    private ObservableCollection _obervableCollection = new ObservableCollection();

    public MainWindow()
    {
        InitializeComponent();
        addColumns();
        addRow();
    }

    void addColumns()
    {
        for (int i = 0; i < 3; i++)
        {
            this.dataGrid.Columns.Add(new DataGridTextColumn() { Header = "Row" + i, Binding = new Binding("[" + i.ToString() + "]") });
        }

        dataGrid.IsReadOnly = true;
        dataGrid.ItemsSource = _obervableCollection;
    }

    void addRow()
    {
        string[] list1 = new string[3] { "1", "2", "3" };
        _obervableCollection.Add(list1);

        string[] list2 = new string[3] { "4", "5", "6" };
        _obervableCollection.Add(list2);

        string[] list3 = new string[3] { "7", "8", "9" };
        _obervableCollection.Add(list3);
    }
}

你可能感兴趣的:(WPF DataGrid 动态列绑定)