开发者

Binding DataGrid to List in wpf

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

pu开发者_开发百科blic 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...

  • first, on your DataGrid control in the XAML mark-up I recommend you set AutoGenerateColumns="False" (you should be able to do this manually better than they can do it automatically)
  • second, on the same control set ItemsSource="{Binding}", which informs the grid it will be getting it's column and row data from a source not defined at design-time.
  • third, construct the columns to look how you want them to look and for each bind to the column data with something like 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.
  • fourth, in your form code-behind, within the constructor or during form load or wherever it best suits your needs, set the DataContext of your grid. This should take a form similar to {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.


In your DataGrid try:

ItemsSource="{Binding Path=.}"

This has worked sucessfully for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜