Reputation: 911
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;}
}
}
Upvotes: 0
Views: 1779
Reputation: 301
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
Upvotes: 0
Reputation: 44068
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}"/>
<DataGridTextColumn Binding="{Binding Name}"/>
<DataGridTextColumn Binding="{Binding HomeAddr.CityName}"/>
<DataGridTextColumn Binding="{Binding HomeAddr.PostCode}"/>
</DataGrid.Columns>
</DataGrid>
Upvotes: 2