I'm 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);
    }
}  
the 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>
The result is that an empty grid is displayed! Anyone know why?
Try setting AutoGenerateColumns = true
(Note: This answer was verified in .NET Framework v4.0):
A simple, 4-part operation...
AutoGenerateColumns="False" (you should be able to do this manually better than they can do it automatically)ItemsSource="{Binding}", which informs the grid it will be getting it's column and row data from a source not defined at design-time.Binding="{Binding Path=UniqueID}".  Note that the value after Path is interpolated so mind things like case-sensitivity.  For the List<> you are targetting the value will presumably be one of the property-names from objects in your target List<>.  Rinse and repeat as many times as needed for each column in your DataGrid.{gridControlName}.DataContext = {target-List<>}
When the form is loaded its grid should auto-populate with content from objects in the your List<>.
Try setting the ItemsSource instead of DataContext, and remove the ItemsSource={Binding} from your XAML. That may do the trick.
Edit:
I just checked some code I wrote that uses the same DataGrid control (WPF Toolkit), and I do in fact set the ItemsSource instead of DataContext. If you need an example, let me know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With