如何设置一个WPF DataGrid的数据源? [英] How to set the DataSource of a DataGrid in WPF?

查看:243
本文介绍了如何设置一个WPF DataGrid的数据源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一个数据库表设置为在一个WPF的GridGrid的数据源。在Windows窗体的属性被称为数据源但在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?

推荐答案

您可以使用<$c$c>ItemsSource属性:

You can use the ItemsSource property :

<ListView ItemsSource="{Binding YourData}">
    <ListView.View>
        <GridView>
            <!-- The columns here -->
        </GridView>
    </ListView.View>
</ListView>

如果您preFER使用code-后面,而不是一个绑定,只给一个名字到的ListView 并设置的ItemsSource 在code属性:

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;

您也可以使用其他列表控件(的DataGrid ListBox中的的ItemsSource 属性组合框等),因为它是在的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.

编辑:如果数据源是一个数据表,你不能直接将其指定为的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屋!

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