如何在 WPF 中设置 DataGrid 的数据源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5398441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the DataSource of a DataGrid in WPF?
提问by Miguel
I need to set a table from a database to be the DataSource of a GridGrid in WPF. In Windows Forms the property is called DataSource
but in WPF no such property exists, so how can i do it?
我需要将数据库中的表设置为 WPF 中 GridGrid 的数据源。在 Windows 窗体中,该属性被调用,DataSource
但在 WPF 中不存在这样的属性,那么我该怎么做呢?
回答by Thomas Levesque
You can use the ItemsSource
property :
您可以使用该ItemsSource
属性:
<ListView ItemsSource="{Binding YourData}">
<ListView.View>
<GridView>
<!-- The columns here -->
</GridView>
</ListView.View>
</ListView>
If you prefer to use code-behind rather than a binding, just give a name to the ListView
and set the ItemsSource
property in code:
如果您更喜欢使用代码隐藏而不是绑定,只需为 命名ListView
并ItemsSource
在代码中设置属性:
listView1.ItemsSource = YourData;
You can also use the ItemsSource
property with other list controls (DataGrid
, ListBox
, ComboBox
, etc), since it is defined in the ItemsControl
base class.
您也可以使用ItemsSource
属性与其他列表控件(DataGrid
,ListBox
,ComboBox
等),因为它是在定义的ItemsControl
基类。
EDIT: if the data source is a DataTable
, you can't assign it directly to ItemsSource
because it doesn't implement IEnumerable
, but you can do it through a binding:
编辑:如果数据源是 a DataTable
,则不能直接将其分配给,ItemsSource
因为它没有实现IEnumerable
,但您可以通过绑定来完成:
listView1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = YourData });
回答by Menard Laval
This is simple an example:
这是一个简单的例子:
XAML part:
XAML 部分:
<DataGrid Name="dataGrid1" Width="866" Height="auto" HorizontalAlignment="Left" VerticalAlignment="Top" />
C# part:
C# 部分:
... [code to read and fill your table ] ...
... [阅读和填写表格的代码] ...
da.Fill(myDataTable);
dataGrid1.ItemsSource = myDataTable.DefaultView;
And now your DataGrid will be filled with your DataTable
现在您的 DataGrid 将填充您的 DataTable
回答by H.B.
The GridView
is a view and not a standalone control as far as i know, you would normally use it as the view of a ListView
. In WPF the property for data population is called ItemsSource
, you probably want to either use a ListView
or DataGrid
to display your data that way.
GridView
据我所知,这是一个视图而不是一个独立的控件,您通常会将它用作ListView
. 在 WPF 中,数据填充的属性称为ItemsSource
,您可能希望使用ListView
或DataGrid
以这种方式显示您的数据。
回答by Subhash Saini
You can use below both ways to bind the datatable to datagrid in WPF.
您可以使用以下两种方式将数据表绑定到 WPF 中的数据网格。
datagrid.ItemSource = mydt.DefaultView();
datagrid.DataContext = mydt.DefaultView();