Binding DataGrid to a list in wpf

I am trying to bind a List to a DataGrid . Here is the code snippet:

 public class Parson { public string LastName { get; set; } public string FirstName { get; set; } public Parson(string lastName, string firstName) { LastName = lastName; FirstName = firstName; } } public class Persons : List<Parson> { // Parameterless constructor public Persons() { } public new void Add(Person parson) { base.Add(parson); } } 

code behind:

 Persons persons = new Persons(); persons.Add(new Parson("New","Person"); dataGrid1.DataContext = persons; 

XAML:

 <my:DataGrid Name="dataGrid1" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" CanUserAddRows="True" ItemsSource="{Binding}" AutoGenerateColumns="False"> <my:DataGrid.Columns> <my:DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}"/> <my:DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}"/> </my:DataGrid.Columns> </my:DataGrid> 

As a result, an empty grid is displayed! Does anyone know why?

+6
data-binding wpf datagrid
source share
4 answers

Try setting AutoGenerateColumns = true

+5
source share

(Note: this answer has been tested in the .NET Framework version 4.0):

Simple operation with 4 parts ...

  • firstly, on your DataGrid control in the XAML markup, I recommend setting AutoGenerateColumns="False" (you have to do it manually better than you can automatically).
  • secondly, in the same control set ItemsSource="{Binding}" , which informs about the grid, it will receive column and row data from a source that was not defined at design time.
  • thirdly, build the columns to see how you want them to look, and for each data binding of a column with something like Binding="{Binding Path=UniqueID}" . Note that the value after Path is interpolated, so consider things like case sensitivity. For List <>, you are targeting a value that is supposed to be one of the property names from the objects in your target List <>. Rinse and repeat as many times as necessary for each column in your DataGrid.
  • fourthly, in your code form, inside the constructor or while loading the form, or where it best suits your needs, set the DataContext of your grid. This should have a form similar to {gridControlName}.DataContext = {target-List<>}

When the form loads, its grid should be automatically filled with the contents of the objects in your list <>.

+5
source share

Try setting ItemsSource instead of DataContext and remove ItemsSource={Binding} from your XAML. This can do the trick.

Edit:

I just checked the code I wrote that uses the same DataGrid control (WPF Toolkit), and I actually set the ItemSource instead of the DataContext. If you need an example, let me know.

+1
source share

In your DataGrid program, try:

 ItemsSource="{Binding Path=.}" 

This works successfully for me.

0
source share

All Articles