将DataGrid绑定到List <dictionary <string,string>&gt;

时间:2015-06-14 12:02:15

标签: c# silverlight datagrid

我正在动态加载我的datagrid列,因为列数在运行时可能会有所不同。列名列表在ProdCatList中检索。我想模拟在QuotationDG Datagrid中添加一行。

以下是我添加列的方式:

 foreach (ProductCategory ProdCat in ProdCatList)
 {
      DataGridColumn ProdCatColumn = new DataGridTextColumn {Binding = new Binding(ProdCat.Name)};
      ProdCatColumn.Header = ProdCat.Name;
       QuotationDG.Columns.Add(ProdCatColumn);
 }

这就是我尝试添加虚拟行的方法:

List<Dictionary<string, string>> mydictlist = new List<Dictionary<string,string>>();
Dictionary<string, string> mydict = new Dictionary<string, string>();
for (int i=0; i<ProdCatList.Count; i++)
{

    mydict.Add(ProdCatList[i].Name, ProdCatList[i].Name);
  }
  mydictlist.Add(mydict);

 QuotationDG.ItemsSource = mydictlist;
}

对于第一个代码,列显示正确,但对于第二个代码,行将添加到DataGrid,但不显示名称(在字典值中),并且所有列都为空。 如何修复此代码以显示添加的行中的数据?

1 个答案:

答案 0 :(得分:0)

如果在循环外定义它,你的mydist类型将使用相同的对象

<nav class="navbar navbar-default">
  <div class="container-fluid">
  <div class="navbar-header">
  <a class="navbar-brand" href="#">My Tool</a>
</div>

  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
      <li><a href="#">FAQ</a></li>
      <li><a href="#">About</a></li>
      <li><a data-toggle="modal" data-target="#myModal">Add Something</a></li>
    </ul>
  </div>
 </div>
</nav>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
 <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title" id="myModalLabel">Modal title</h4>
  </div>
  <div class="modal-body">
    ...
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>
  </div>
</div>