Search code examples
c#wpfwpfdatagrid

how to bind a datagrid with a class contains object of another class


sry but i`m new with wpf, i have a class called generatedMessage and am trying to bind it with a datagrid.

class generatedMessage
{
    public CanMessage cmsg { set; get; }
    public int cycleTime { set; get; }
    public generatedMessage(){}
}
public class CanMessage
{
    public byte[] data { set; get; }
    public ushort dlc { set; get; }
    public ushort flags { set; get; }
    public uint id { set; get; }
    public ulong res1 { set; get; }
    public ulong res2 { set; get; }
}

as u see generatedMessage class have an object of CanMessage class, i have done this before with the CanMessage class like below

TraceTable.Items.Add /*- at TraceTable is a datagrid -*/
(
   new CanMessage()
   {
       data = msg.data,
       dlc = msg.dlc,
       id = msg.id,
       flags = msg.flags,
       res1 = msg.res1,
       res2 = msg.res2
   }
);
//xml file below
 <DataGrid x:Name="TraceTable" Grid.Column="0" DockPanel.Dock="Top" SelectionMode="Extended" AutoGenerateColumns="False" SelectionUnit="FullRow" Margin="0,45,4,0">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=data}"  Header="Data" IsReadOnly="true"/>
        <DataGridTextColumn Binding="{Binding Path=dlc}" Header="DLC" IsReadOnly="true"/>
        <DataGridTextColumn Binding="{Binding Path=id}"  Header="ID" IsReadOnly="true"/>
        <DataGridTextColumn Binding="{Binding Path=flag}" Header="Flag" IsReadOnly="true"/>
        <DataGridTextColumn Binding="{Binding Path=res1}"  Header="Res1" IsReadOnly="true"/>
        <DataGridTextColumn Binding="{Binding Path=res2}" Header="Res2" IsReadOnly="true"/>
    </DataGrid.Columns>
 </DataGrid>

so my question is how to make it with generatedMessage class ? i want the datagrid to view all canMessage attributes + cycle time (a datagrid with 7 columns)


Solution

  • If I understand question properly, then you should add items of type "generatedMessage" and do binding like:

    Binding={Binding cycleTime}
    Binding={Binding cmsg.dlc}
    ...
    etc.
    



    Generally you shouldn't add items manually to DataGrid. The best way to do it: create ObservableCollection in a ViewModel and set attribute "ItemsSource" in DataGrid:

    ItemsSource="{Binding Collection}"
    

    then add items to this collection, not to DataGrid. To better understood that topic you could read about MVVM pattern ;-).