Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind List to DataGrid

I have a problem binding a List to a DataGrid in WPF. Let me explain what I have tried.

public struct SomeInfo
{
    public string Name;
    public string Description;
    public string ID;
}

List<SomeInfo> arrSomeInfo;

The arrSomeInfo contains multiple items of structure SomeInfo.

The DataGrid Looks something like:

<DataGrid Name="grdMailbag" AutoGenerateColumns="False" ItemsSource="{Binding}">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="cID" Binding="{Binding ID}" Header="ID" />
        <DataGridTextColumn x:Name="cName" Binding="{Binding Name}" Header="Name" />
        <DataGridTextColumn x:Name="cDescription" Binding="{Binding Description}" Header="Description" />
    </DataGrid.Columns>
</DataGrid>

I have tried the following without success:

this.grdMailbag.ItemsSource = arrSomeInfo; //Didn't worked
this.grdMailbag.DataContext= arrSomeInfo;  // Didn't worked

What is happening is that it is adding the rows as per List arrSomeInfo but all the rows are blank.

like image 568
chrismasters Avatar asked Aug 05 '13 21:08

chrismasters


1 Answers

Change this:

public struct SomeInfo
{
    public string Name;
    public string Description;
    public string ID;
}

to this:

public class SomeInfo
{
    public string Name {get;set;}
    public string Description {get;set;}
    public string ID {get;set;}
}

WPF does not support binding to fields. Only properties. And a struct is not an appropiate type for the data you're trying to represent.

like image 82
Federico Berasategui Avatar answered Oct 26 '22 18:10

Federico Berasategui