几点说明
- 这里主要是参考了MSDN中关于DataGrid的说明
- 这里只会简单说明在WPF中,DataGird最简单的使用方法
- 对于MSDN中的翻译不会很详细,也不会每一句都翻译。
来自MSDN的内容
| Type | Name | Description |
| Constructors | DataGrid | Initializes a new instance of the System.Windows.Controls.DataGrid class. |
| Property | ItemsSource | Gets or sets a collection that is used to generate the content of the control. |
| AutoGenerateColumns | Gets or sets a value that indicates whether columns are created automatically when the ItemsSource property is set. |
The DataGrid control provides a flexible way to display a collection of data in rows and columns. The built-in column types include a text box column, a check box column, and a template column for hosting custom content. The built-in row type includes a drop-down details section that you can use to display additional content below the cell values.
内建的列类型包括:
- 文本框
- 复选框
- 模板列
内建的行类型包括:
- 下拉列表
Binding to Data
To bind the DataGrid to data, set the ItemsSource property to an IEnumerable implementation. Each row in the data grid is bound to an object in the data source, and each column in the data grid is bound to a property of the data object. In order for the DataGrid user interface to update automatically when items are added to or removed from the source data, the DataGrid must be bound to a collection that implements INotifyCollectionChanged, such as an ObservableCollection(Of T). In order to automatically reflect property changes, the objects in the source collection must implement the INotifyPropertyChanged interface.
绑定数据
System.Windows; using System.Collections.ObjectModel; namespace csdemo.wpf.controls.DataGrid { /// <summary> /// DataGridWindow.xaml 的交互逻辑 /// </summary> public partial class DataGridWindow : Window { public DataGridWindow() { InitializeComponent(); dtgrdDisplay.DataContext = gridList; } ObservableCollection<GirdDataItem> gridList = new ObservableCollection<GirdDataItem>(); private void btnAdd_Click(object sender, RoutedEventArgs e) { GirdDataItem item = new GirdDataItem(); item.id = gridList.Count + 1; item.item = tbItem.Text.Trim(); gridList.Add(item); } private void btnReset_Click(object sender, RoutedEventArgs e) { gridList.Clear(); dtgrdDisplay.ItemsSource = null; } private void btnClose_Click(object sender, RoutedEventArgs e) { this.Close(); } } public class GirdDataItem { private int _id; public int id { get { return _id; } set { _id = value; } } private string _item; public string item { get { return _item; } set { _item = value; } } } }
- 设置ItemsSource属性为一个IEnumerable接口的实现(作为数据源)
- DataGird中的每一行都绑定到在数据源中的一个对象,每一列都绑定到数据对象中的一个属性
- 为了使用户接口能够在items增加或减少时能够从数据源自动更新,DataGrid必须绑定到一个INotifyCollectionChanged接口的实现集上,就像ObservableCollection(Of T)
- 为了自动反应属性的变化,在数据源中的对象集必须实现INotifyPropertyChanged接口。