Kobe-Wan Kenobi
Kobe-Wan Kenobi

Reputation: 3864

Binding to a collection in WPF

I have a problem trying to bind a DataGrid to a List, or to a Dictionary. If I set DataContext to an object, and set ItemSource to a List property of that object, I get DataGrid populated with List count, in case of a List, why? How can I bind properly to a List, and how to a Dictionary?

List<string> con = new List<string>();
        con.Add("aaaddd");
        con.Add("bbb");
        this.DataContext = con;

<DataGrid AutoGenerateColumns="True" Height="104" HorizontalAlignment="Left"          Margin="34,171,0,0" Name="dg" VerticalAlignment="Top" Width="421" ItemsSource="{Binding}"/>

And I get populated with

Length 6 3

Why? And how to bind to a Dictionary?

Upvotes: 1

Views: 91

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81253

Problem is you have set AutoGenerateColumns to True on your dataGrid.

When AutoGenerateColumns is set to true than columns are auto generated based on the properties exposed by the underlying object which is in your case is string which only exposes single property i.e. Length.

In case you want to get the value of string, you need to set that property to false and provide your own columns collection. This will work -

    <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Value"
                                IsReadOnly="True"
                                Binding="{Binding}"/>
        </DataGrid.Columns>
    </DataGrid>

Upvotes: 1

HichemSeeSharp
HichemSeeSharp

Reputation: 3318

As said in the comment, I think you're refering to WPF's DataGrid Control.
If you're setting the list object to the DataContext then just ItemsSource="{Binding}" this will bind to the DataContext root which is your list object.

Upvotes: 1

Related Questions