1
votes

I have just recently started using WPF (.NET 4.0), not using proper MVVM.

So I have a

SortedList<int, Person>

Person is a class having the public members: Name, Age, Address.

I would like to show only the Person and the Name, Age, Address fields in the DataGrid. How on earth do I do that? DataContext, ItemSource? And it must be a SortedList because the order of the Persons is very important.

Please, any help appreciated!

2

2 Answers

1
votes

please try this method: XAML:

<DataGrid x:Name="dataGrid" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Value.Name}"/>
        <DataGridTextColumn Header="Age" Binding="{Binding Value.Age}"/>
        <DataGridTextColumn Header="Address" Binding="{Binding Value.Address}"/>
    </DataGrid.Columns>
</DataGrid>

Code-Behind:

private void dataGridInit()
{
    SortedList<int, Person> list = new SortedList<int, Person>();
    list.Add(2, new Person() {Name = "James", Age = 30, Address = "some place" });
    list.Add(1, new Person() { Name = "Kitty", Age = 28, Address = "some place" });
    list.Add(3, new Person() { Name = "Deko", Age = 28, Address = "some place" });

    dataGrid.DataContext = list;
    dataGrid.ItemsSource = list;
}

Person Class:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
}
1
votes

When you set ItemsSource to your SortedList each item will be of KeyValuePair<int, Person> type so you can get Value and this will have your Name, Age and Address property

<DataGrid AutoGenerateColumns="False">
    <DataGridTextColumn Header="Name" Binding="{Binding Path=Value.Name}"/>
    <DataGridTextColumn Header="Age" Binding="{Binding Path=Value.Age}"/>
    <DataGridTextColumn Header="Address" Binding="{Binding Path=Value.Address}"/>
</DataGrid>