I am having some problems when I have a datatable and I want to bind each datagridtextcolumn in the datagrid to each column in the datatable.
my code is as below
public class Packet
{
public Header header { get; set; }
public Frame frame { get; set; }
public Tail tail { get; set; }
public String id { get; set; }
public Packet(String id,Header header, Frame frame, Tail tail)
{
this.id = id;
this.header = header;
this.frame = frame;
this.tail = tail;
}
}
Hence on my xaml side
<Grid >
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=.}" Name="dgrid" SelectionChanged="dgrid_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path=id}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
And on my code side, ds is a dataset which has one datatable. Each row is a packet 4 columns corresponding to header frame tail and id. I am trying to get the id to bind correctly first. But the id number cannot display on the datagrid.
dgrid.DataContext = ds.Tables[0];
It actually displays the correct data if i do not use the datagridtextcolumn on the xaml side. but what i wanted is to do the binding on the xaml side to the datatable.
Try this
<Grid >
<DataGrid AutoGenerateColumns="False" Name="dgrid" SelectionChanged="dgrid_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path=id}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
dgrid.ItemsSource = ds.Tables[0].AsDataView();
If you have a model class like Packet
in your case, then I would suggest to use observable collection instead of DataTable
to hold the list of Packets
. DataTable
's item is of type DataRowView
.
I am not even sure how is your DataTable
holding a Packet
instance?
If your ds.Tables[0].Rows[0] of Packet
type or ds.Tables[0].Rows[0] [0] is of Packet
type?
If so that would cause lot of trouble for binding.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.