iato
iato

Reputation: 434

Datagrid Items.Add not displaying content - WPF/XAML

I have a datagrid called dgFiles that has 4 columns and populates each column with a string. When I go to add a Item to my datagrid using

//Add Row
MessageBox.Show(fileName + " " + dateModified + " " + fileType + " " + fileLength);
dgFiles.Items.Add(new object[] { fileName, dateModified, fileType, fileLength + " kb" });
dgFiles.Items.Refresh();

the messagebox displays the correct strings I want to populate my datagrid with, however my datagrid simply displays a blank row.

dgFiles

The code to my XAML Datagrid

    <!--Data Grid-->
    <DataGrid x:Name="dgFiles" Grid.Row="4" Margin="5" GridLinesVisibility="None" IsReadOnly="True" RowHeaderWidth="0" MouseDoubleClick="dgFiles_MouseDoubleClick">
        <DataGrid.Columns>
            <DataGridTextColumn Header="File Name"      Width="30*"/>
            <DataGridTextColumn Header="Date Modified"  Width="40*"/>
            <DataGridTextColumn Header="Type"           Width="14*"/>
            <DataGridTextColumn Header="Size"           Width="10*"/>
        </DataGrid.Columns>
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="BorderThickness" Value="0"></Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGrid.CellStyle>
    </DataGrid>

Any help would be greatly appreciated :)

Thanks, iato

Upvotes: 0

Views: 8386

Answers (1)

mm8
mm8

Reputation: 169420

You need to set the Binding property of each column to a binding that binds to a public property of the data item that you add to the Items/ItemsSource collection:

<DataGridTextColumn Header="File Name" Binding="{Binding Filename}" Width="30*"/>
<DataGridTextColumn Header="Date Modified" Binding="{Binding Date}" Width="40*"/>
<DataGridTextColumn Header="Type" Binding="{Binding Type}" Width="14*"/>
<DataGridTextColumn Header="Size" Binding="{Binding Size}" Width="10*"/>

This also means that your data object must expose public properties:

dgFiles.Items.Add(new { FileName = fileName, Date = dateModified, Type = fileType, Size = fileLength + " kb" });

If you want to be able to edit the data in the DataGrid you cannot add anonymous objects to its Items property though. Instead you should define a class with your properties and set the ItemsSource to an IEnumerable of this type:

List<YourClass> items = new List<YourClass>();
items.Add(new YourClass { FileName = fileName, Date = dateModified, Type = fileType, Size = fileLength + " kb" });
dgFiles.ItemsSource = items;

Upvotes: 4

Related Questions