简体   繁体   English

如何在 WPF 中设置 DataGrid 的数据源?

[英]How to set the DataSource of a DataGrid in WPF?

I need to set a table from a database to be the DataSource of a GridGrid in WPF.我需要将数据库中的表设置为 WPF 中 GridGrid 的数据源。 In Windows Forms the property is called DataSource but in WPF no such property exists, so how can i do it?在 Windows 窗体中,该属性称为DataSource ,但在 WPF 中不存在此类属性,那么我该怎么做呢?

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属性与其他列表控件( DataGridListBoxComboBox等)一起使用,因为它是在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:编辑:如果数据源是DataTable ,则不能将其直接分配给ItemsSource因为它没有实现IEnumerable ,但您可以通过绑定来实现:

listView1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = YourData });

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

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

You can use below both ways to bind the datatable to datagrid in WPF.您可以使用以下两种方式将数据表绑定到 WPF 中的数据网格。

 datagrid.ItemSource = mydt.DefaultView();

 datagrid.DataContext = mydt.DefaultView();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM