Search code examples
c#wpfwpfdatagrid

How to Binding the array[] to the DataGridTextColumn dynamiclly wpf


When I have a Staff class ,I want to Binding the TB[] to the DataGrid Columns Staff.cs

public class Staff
{
    public string Name { get; set; }
    public float? Test_Score { get; set; }
    public float? Net_Income_Tax { get; set; }
    public float temp { get; set; }
    public float[] TB = new float[100];
    public float TB_Sum { get; set; }

}

in the Page,my code are as follows:

public ObservableCollection<Staff> Staff_Show = new ObservableCollection<Staff>();
public int StaffShowSize;

public TaxBefore_Sum(ObservableCollection<Staff> StaffAccept)
{

    InitializeComponent();
    Staff_Show = StaffAccept;
    StaffShowSize = Staff_Show.Count;


    DataGrid1.ItemsSource = this.Staff_Show;

    //this is to dynamiclly to create new DataGridTextColumn,but 
    //final ,only create the columns' header is"0",and no data to show,however,the TB[i] have data,but can't show like the picture
    for (int i = 0; i < StaffShowSize; i++)
    {
        DataGridTextColumn c = new DataGridTextColumn();
        c.Header = Convert.ToString(i + 1);
        c.Binding = new Binding("TB[i]");
        DataGrid1.Columns.Add(c);
    }
}

the "for()" sentence is to dynamiclly to create new DataGridTextColumn,but final ,only create the columns' with header,and no data to show,however,the TB[i] have data,but can't show like the picture:enter image description here

when I changed the code to

c.Binding = new Binding("TB[" + i + "]");

it showns that enter image description here


Solution

  • Here is what you need...

    c.Binding = new Binding("TB[" + i + "]");
    

    Also definition of TB...

    public float[] TB { get; set; }  = new float[100];