如何在 WPF 中设置 DataGrid 的数据源? [英] How to set the DataSource of a DataGrid in WPF?
问题描述
我需要将数据库中的表设置为 WPF 中 GridGrid 的数据源.在 Windows 窗体中,该属性被称为 DataSource
但在 WPF 中不存在这样的属性,那么我该怎么做?
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?
推荐答案
您可以使用 ItemsSource
属性:
You can use the ItemsSource
property :
<ListView ItemsSource="{Binding YourData}">
<ListView.View>
<GridView>
<!-- The columns here -->
</GridView>
</ListView.View>
</ListView>
如果您更喜欢使用代码隐藏而不是绑定,只需为 ListView
命名并在代码中设置 ItemsSource
属性:
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:
listView1.ItemsSource = YourData;
您还可以将 ItemsSource
属性与其他列表控件(DataGrid
、ListBox
、ComboBox
等)一起使用),因为它是在 ItemsControl
基类中定义的.
You can also use the ItemsSource
property with other list controls (DataGrid
, ListBox
, ComboBox
, etc), since it is defined in the ItemsControl
base class.
如果数据源是DataTable
,则不能直接将其分配给ItemsSource
,因为它没有实现IEnumerable
,但您可以通过绑定来实现:
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:
listView1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = YourData });
这篇关于如何在 WPF 中设置 DataGrid 的数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!