Bak Itzik
Bak Itzik

Reputation: 486

WPF - Printing Array property in GridView

I have a List of this class:

public class A
{
    public string Name{ get; set; }
    public int ID { get; set; }
    public B[] B_details { get; set; } 
    public int phone { get; set; }

}

which I want to show in GridView. Class B also have some properties, with property Name among them. My grid definition is:

<Grid>
    <DataGrid AutoGenerateColumns="True" Name="dataGrid1" IsReadOnly="True" AlternationCount="2" />
</Grid>

The problem is, because it is AutoGenerated GridView - the values in the B_details column are all show up in the form "B[] Array". How can I show the Names of all the B members of this class?

Upvotes: 1

Views: 858

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

I can think of two ways:

1) Use a class instead of B[], and override its ToString() method. So you'd have something like:

public class BArray : List<B>
{
    public override void ToString()
    {
        return string.Join(Items.Select(item => item.Name), ", ");
    }
}

That way a comma-separated list of B.Name will get printed in the DataGrid column.

2) Turn off the auto-generated columns, and specify a DataTemplate for the B_details column. Eg:

<DataGrid.Columns>
    <!-- insert other columns -->
    <DataGridTemplateColumn Header="B Details">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding B_details}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Name}" Margin="0,0,5,0" />
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal" />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
<DataGrid.Columns>

Upvotes: 1

Related Questions