在 WPF 中,如何将数据网格列绑定到数据表的特定列?
我有一个包含许多列的数据表和一个数据网格,我只需要在其中显示其中的几列。我需要一个如何做到这一点的代码示例。我发现一大堆例子告诉我将 AutoGenerateColumns 设置为 true 并将表设置为 DataContext 以显示 DataTable 中的所有列。我想我可以放入一页代码来隐藏所有不需要的列,将剩余的列重新排列为正确的顺序和大小,但肯定有一种更优雅的方式。
在设计器中,我已经构建了要显示的列的集合,我得到了数据表,如何将现有的数据网格列绑定到代码中的特定数据表列?
I have a Datatable with many columns, and a datagrid in which I need to display only a few of those columns. I need a codesample of how to do it. I found a whole bunch of examples telling me to turn AutoGenerateColumns to true and set the table as DataContext to display all the columns in my DataTable. And I guess I could then put in a page of code to hide all the columns that I don't need, rearrange the leftover ones to proper order and size, but surely there must be a more elegant way.
In designer I have build the collection of columns I want to display, I got the datable, how do I bind an existing datagrid column to a specific datatable column in my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 DataTable 绑定到 DataGrid,将 AutoGenerateColumns 设置为 False,然后将所需的任何列添加到 DataGrid.Columns。下面是一个使用名为 Collection 的 DataTable 的示例,其中包含两列:ID 和 Value。
Bind your DataTable to the DataGrid, set the AutoGenerateColumns to False, and then add whatever columns you want to DataGrid.Columns. Here's an example using a DataTable called Collection, with two columns: ID and Value.
XAML 绑定对我不起作用,因为我的
DataTable
是在运行时生成的,因此在设计时没有任何内容可以绑定。不管怎样,我偶然发现了如何在这里做我想做的事。我的问题是因为由于某种原因,当我将
ItemSource
设置为表本身而不是表的DefaultView
时,没有抛出错误,尽管我后来读到,该表未实现所需的接口。但是,如果没有任何错误告诉我差异,我就无法继续查找为什么我的网格会显示为空。XAML binding would not work for me because my
DataTable
is generated at runtime so there is nothing to bind to at design time. Anyway, I stumbled on how to do what I wanted here.My problems were because for some reason there was no error thrown when I would set
ItemSource
to the table itself, instead of the table'sDefaultView
, even though, as I later read, the table does not implement the required interface. But without any errors to tell me difference I had nothing to go on to find why my grid would display as empty.