简体   繁体   中英

How to bind collection to datagrid column in WPF

I have the following model:

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);

        }
    }
 }

I am binding the collection to datagrid in Xaml using:

<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>

How can I add another column to bind Specifications? I tried:

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

But I am getting

can not resolve Specifications in data context

Here is a solution with ListBox:

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

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