如何将集合绑定到WPF中的datagrid列

时间:2018-02-05 08:21:40

标签: c# wpf data-binding datagrid

我有以下型号:

public class Order
{
 public Order()
 {
    Specifications = new List<string>();
 }
 public Guid Id { get; set; }
 public DateTime CreateDate { get; set; }
 public ICollection<string> Specifications { get; set; }
}

 public class Context: INotifyPropertyChanged
 {
    private ObservableCollection<Order> orders;
    public ObservableCollection<Order> Orders
    {
        get { return orders; }
        set
        {
            orders = new ObservableCollection<Order>(value);

        }
    }
 }

我使用以下方法将集合绑定到Xaml中的datagrid:

<Window.DataContext>
        <viewModel:Context/>
</Window.DataContext>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Orders}" HorizontalAlignment="Stretch" Margin="5" Name="dgUserList" VerticalAlignment="Stretch" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Id}"/>
                <DataGridTextColumn Binding="{Binding CreateDate}" />
            </DataGrid.Columns>
</DataGrid>

如何添加另一列来绑定规范?我试过了:

<DataGridTemplateColumn>
           <DataGrid ItemsSource="{Binding Specifications}"></DataGrid>
 </DataGridTemplateColumn>

但我得到了

  

无法解析数据上下文中的规范

1 个答案:

答案 0 :(得分:2)

以下是ListBox的解决方案:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ListBox ItemsSource="{Binding Specifications}"></ListBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>