tags:

views:

333

answers:

3

I 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 display! anyone know why?

A: 

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.

Pwninstein
I tried. Does not work for me.Please give me code example.
Anibas
A: 

In your DataGrid try:

ItemsSource="{Binding Path=.}"

This has worked sucessfully for me.

ChrisF
didn't worked for me...
Anibas
A: 

I'm not sure that you can bind directly to a pure List object, I think that your "Persons" List object needs to be an ObservableCollection, or BindingList or other collection that can be bound to.

StrayPointer
Binding to the List will work, it just won't add rows to the DataGrid if new Persons are added after the binding happens. WPF has no problem binding one time to any IEnumerable, just like it has no problem binding one time to a property that doesn't implement INotifyPropertyChanged.
Abe Heidebrecht
Ok, thanks for the correction. I'm still learning WPF and made an incorrect assumption based on what I've observed elsewhere.
StrayPointer