Search code examples
c#wpfdatagridsorteddictionary

How to display a SortedDictionary in DataGrid WPF?


I want to display a sortedDictionary in the dataGrid when the key is int and value is List of ClassType for example value-List of Persons.

For the example:

public MainWindow()
    {
        InitializeComponent();
        SortedDictionary<int, List<Person>> Sd1 = new SortedDictionary<int,List<Person>>();
        Person p1 = new Person("htryh");
        Person p2 = new Person("juyik");
        List<Person> PL = new List<Person>();
        PL.Add(p1);
        PL.Add(p2);
        Sd1.Add(1, PL);
        dt1.ItemsSource = Sd1;

    }
}
class Person
{
    public string Name { get; set; }
    public Person(string name)
    {
        Name = name;
    }
}

In the dataGrid in the column "Key" i see the int , but in the column "value" i see: (Collection). How do i solve this?? Thanks.


Solution

  • Set AutoGenerateColumns to False on dataGrid and provide your own set of columns.

    <DataGrid x:Name="dt1" AutoGenerateColumns="False" IsReadOnly="True">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Key" Binding="{Binding Key}"/>
            <DataGridTemplateColumn Header="Value">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox ItemsSource="{Binding Value}"
                                    IsSynchronizedWithCurrentItem="True"
                                    DisplayMemberPath="Name"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>