简体   繁体   中英

How to bind DataGrid to a second-level property of a data source?

Suppose you write up code for a class Person whose properties are composed of primitive types and a class Address whose properties are all primitive types. You put multiple Person objects in an ObservableCollection and you want to bind it to a DataGrid. The properties with primitive types will display normally, but the property Address , that is a class composed of primitive types, will just display "(Collection)".

I found a solution to this problem while googling, but it seems like a lot of work for a little functionality. The solution I found was for DataGridView and it was dated for 2007. Is there an easier way now that we can use WPF and DataGrid or is it just as difficult?

Example code:

class Person
{
    private string id;
    private string name;
    private Address homeAddr;

    public string ID
    {
            get { return id;}
            set { id = value;}
    }

    public string Name
    {
            get { return name;}
            set { name = value;}
    }

    public Address HomeAddr
    {
            get { return homeAddr;}
            set { homeAddr = value;}
    }
}

class Address
{
    private string cityname;
    private string postcode;

    public string CityName
    {
        get { return cityname;}
        set { cityname = value;}
    }

    public string PostCode
    {
        get { return postcode;}
        set { postcode = value;}
    }
}
<DataGrid>
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Id}"/>
    <DataGridTextColumn Binding="{Binding Name}"/>
    <DataGridTextColumn Binding="{Binding HomeAddr.CityName}"/>
    <DataGridTextColumn Binding="{Binding HomeAddr.PostCode}"/>
  </DataGrid.Columns>
</DataGrid>

The reason why you can't add the Address directly to your DataGrid column is because that column expects a primitive type and you send an "Address" type object. To fix this, you must create a Converter that transforms your Address object into a primitive type, like a string.

First add your converter in the Resource Dictionary

<src:AddressToStringConverter x:Key="AddressToStringConverter" />

and afterwards use it in your grid

<DataGrid>
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Id }"/>
    <DataGridTextColumn Binding="{Binding Name}"/>
    <DataGridTextColumn Binding="{Binding HomeAddr, Converter={StaticResource AddressToStringConverter}}"/>
  </DataGrid.Columns>
</DataGrid>

Here you can find out more about converters : http://wpftutorial.net/ValueConverters.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM