简体   繁体   English

将列表项绑定到数据网格

[英]Binding list items to the datagrid

I have a problem with binding. 我绑定有问题。 I want to bind list items to the datagrid columns. 我想将列表项绑定到datagrid列。 One row in datagrid represents one list of items. datagrid中的一行代表一个项目列表。 Every item is in a column. 每个项目都在一列中。 For example, all items from lists with index 0 are in column with index 0. 例如,索引为0的列表中的所有项目都在索引为0的列中。

My datagrid: 我的数据网格:

<DataGrid Name="AttacksForGroupsDG" 
              CanUserAddRows="False"
              CanUserDeleteRows="True"
              AutoGenerateColumns="False"
              DockPanel.Dock="Top"
              VerticalAlignment="Stretch"
              HorizontalAlignment="Stretch"
              Height="250">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Jméno vesnice" Binding="{Binding Name}" Width="120"/>
            <DataGridTextColumn Header="Souřadnice" Binding="{Binding Coords}" Width="70"/>
        </DataGrid.Columns>
    </DataGrid>

Next, I have a list of items to which I bind to. 接下来,我列出了要绑定到的项目。 Every item of this list represents one row in my datagrid. 该列表的每一项代表我的数据网格中的一行。

public abstract class Group<T>
    where T : Village
{
    public ObservableCollection<T> Villages { get; private set; }

    // the rest of the code I deleted for a clarity
}

Finally, I bind to this class. 最后,我绑定到该类。 The properties Name and Coords I inherit from a class Village. 我从类Village继承的Name和Coords属性。

public sealed class Def : Village
{
    public List<int> Attacks { get; set; }

    public Def()
        : base()
    {
        Attacks = new List<int>();
    }
}

So, the first column in the datagrid will be with the Name property. 因此,数据网格中的第一列将具有Name属性。 The second column will be with the Coords property. 第二列将包含Coords属性。 The next columns I create dynamically in code according to the number of items in the list Attacks in the class Def. 我将根据Def类中的Attacks列表中的项目数量在代码中动态创建的下一列。

I don't know how to bind items from that list to individual columns. 我不知道如何将列表中的项目绑定到各个列。

I appreciate any advice. 我感谢任何建议。

Add the ItemSource attribute to your DataGrid tag with a binding on your Villages list: 将ItemSource属性添加到您的DataGrid标记,并在Villages列表上进行绑定:

     <DataGrid Name="AttacksForGroupsDG" 
          CanUserAddRows="False"
          CanUserDeleteRows="True"
          AutoGenerateColumns="False"
          DockPanel.Dock="Top"
          VerticalAlignment="Stretch"
          HorizontalAlignment="Stretch"
          Height="250"
          ItemsSource="{Binding Villages}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Jméno vesnice" Binding="{Binding Name}" Width="120"/>
            <DataGridTextColumn Header="Souřadnice" Binding="{Binding Coords}" Width="70"/>
        </DataGrid.Columns>
    </DataGrid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM