在WPF中,如何将datagrid列绑定到datatable的特定列? [英] In WPF, how can I bind a datagrid column to a specific column of a datatable?

查看:587
本文介绍了在WPF中,如何将datagrid列绑定到datatable的特定列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Datatable,其中有很多列,还有一个datagrid,我只需要显示其中的几列。我需要一个如何做的代码示例。我发现一大堆示例告诉我将AutoGenerateColumns设置为true,并将该表设置为DataContext以显示DataTable中的所有列。我想我可以放入一个代码页面来隐藏我不需要的所有列,将剩余的列重新排列成正确的顺序和大小,但肯定会有一个更优雅的方式。



在设计器中,我已经构建了我要显示的列的集合,我得到了datable,我如何将现有的datagrid列绑定到我的代码中的特定datatable列

解决方案

将DataTable绑定到DataGrid,将AutoGenerateColumns设置为False,然后添加所需的任何列DataGrid.Columns 。以下是使用名为Collection的DataTable的示例,其中包含两列:ID和值。

 < DataGrid 
ItemsSource = {Binding Path = Collection}
AutoGenerateColumns = False
>

< DataGrid.Columns>
< DataGridTextColumn Header =IdBinding ={Binding Path = Id}/>
< DataGridTextColumn Header =ValueBinding ={Binding Path = Value}/>
< /DataGrid.Columns>
< / DataGrid>


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?

解决方案

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.

<DataGrid
    ItemsSource="{Binding Path=Collection}"
    AutoGenerateColumns=False
    >

    <DataGrid.Columns>
        <DataGridTextColumn Header="Id" Binding="{Binding Path=Id}" />
        <DataGridTextColumn Header="Value" Binding="{Binding Path=Value}" />
    </DataGrid.Columns>
</DataGrid>

这篇关于在WPF中,如何将datagrid列绑定到datatable的特定列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆