如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:41:30  来源:igfitidea点击:

How to set the DataSource of a DataGrid in WPF?

wpfwpf-controlsbindingwpfdatagrid

提问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 DataSourcebut in WPF no such property exists, so how can i do it?

我需要将数据库中的表设置为 WPF 中 GridGrid 的数据源。在 Windows 窗体中,该属性被调用,DataSource但在 WPF 中不存在这样的属性,那么我该怎么做呢?

回答by Thomas Levesque

You can use the ItemsSourceproperty :

您可以使用该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 ListViewand set the ItemsSourceproperty in code:

如果您更喜欢使用代码隐藏而不是绑定,只需为 命名ListViewItemsSource在代码中设置属性:

listView1.ItemsSource = YourData;

You can also use the ItemsSourceproperty with other list controls (DataGrid, ListBox, ComboBox, etc), since it is defined in the ItemsControlbase class.

您也可以使用ItemsSource属性与其他列表控件(DataGridListBoxComboBox等),因为它是在定义的ItemsControl基类。



EDIT: if the data source is a DataTable, you can't assign it directly to ItemsSourcebecause 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 GridViewis 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 ListViewor DataGridto display your data that way.

GridView据我所知,这是一个视图而不是一个独立的控件,您通常会将它用作ListView. 在 WPF 中,数据填充的属性称为ItemsSource,您可能希望使用ListViewDataGrid以这种方式显示您的数据。

回答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();