我有一个Customer对象列表,我想在DataGrid中显示。我通过代码绑定了List:
dataGrid.DataContext = customers;
每位客户都有一个或多个电话号码。我想在客户的行/记录中列出它们。我该怎么做呢? 我的DataGrid在XAML中看起来像这样:
<DataGrid AutoGenerateColumns="False" Height="212" IsReadOnly="True"
HorizontalAlignment="Left" Margin="12,41,0,0" ItemsSource="{Binding}"
Name="dataGrid" VerticalAlignment="Top" Width="932">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=LastName}" Header="Porting ID"/>
<DataGridTextColumn Binding="{Binding Path=FirstName}" Header="Operator" />
</DataGrid.Columns>
</DataGrid>
Customer类是:
public class Customer
{
public String LastName { get; set; }
public String FirstName { get; set; }
public List<Phonenumber> PhoneNumbers { get; set; }
}
PhoneNumber类是:
public class PhoneNumber
{
public String AreaCode {get;set;}
public String Number {get;set;}
}
答案 0 :(得分:4)
首先将itemssource设置为customers而不是datacontext。现在问题:您可以使用DataGridTemplateColumn并绑定到您的phonenumbers集合。此模板列的datatemplate可以是一个简单的itemscontrol。
编辑:
<DataGridTemplateColumn Header="Phonenumbers">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding Phonenumbers}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding AreaCode}" Margin="0,0,5,0"/>
<TextBlock Text="{Binding Number}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
ps:如果您发布代码,我会更新模板;)