【问题标题】:Binding list items to the datagrid将列表项绑定到数据网格
【发布时间】:2016-04-30 09:54:32
【问题描述】:

我遇到了绑定问题。我想将列表项绑定到数据网格列。 datagrid 中的一行代表一个项目列表。每个项目都在一列中。例如,索引为 0 的列表中的所有项目都在索引为 0 的列中。

我的数据网格:

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

接下来,我有一个我绑定到的项目列表。此列表中的每一项都代表我的数据网格中的一行。

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
}

最后,我绑定到这个类。我从类 Village 继承的属性名称和坐标。

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

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

因此,数据网格中的第一列将带有 Name 属性。第二列将包含 Coords 属性。我根据类 Def 中的攻击列表中的项目数在代码中动态创建接下来的列。

我不知道如何将该列表中的项目绑定到各个列。

感谢任何建议。

【问题讨论】:

  • 前 2 列是固定的,然后可以有无限的列?
  • @AnjumSKhan 没错。我在 XAML 中创建前两列,并根据列表的大小在代码中创建其他列。
  • google 搜索:wpf datagrid 可变列数
  • 谢谢。我没有想到。帮我完成了这个教程:elegantcode.com/2010/03/08/…

标签: c# wpf data-binding wpfdatagrid


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2012-06-13
    • 2021-07-12
    • 2016-07-19
    • 2011-01-31
    相关资源
    最近更新 更多