How to: Bind a Grid to Data (eXpress Persistent Objects)
- 2 minutes to read
- Create a new WPF application.
Add reference to the DevExpress.Xpo assembly.
Create a new persistent class representing a data object. To do this, add a new Persistent Object x.x item to the project as shown below.
Implement the ProductDataObject class as shown below.
using System; using DevExpress.Xpo; namespace DXGrid_BindingToXPODataSource { public class ProductDataObject : XPObject { public ProductDataObject() : base() { // This constructor is used when an object is loaded from a persistent storage. // Do not place any code here. } public ProductDataObject(Session session) : base(session) { // This constructor is used when an object is loaded from a persistent storage. // Do not place any code here. } public override void AfterConstruction() { base.AfterConstruction(); // Place here your initialization code. } private string fProductName; public string ProductName { get { return fProductName; } set { SetPropertyValue<string>("ProductName", ref fProductName, value); } } private int fUnitPrice; public int UnitPrice { get { return fUnitPrice; } set { SetPropertyValue<int>("UnitPrice", ref fUnitPrice, value); } } } }
Define a database to store data.
private void InitDAL() { XpoDefault.DataLayer = XpoDefault.GetDataLayer( AccessConnectionProvider.GetConnectionString(@"c:\database\product.mdb"), AutoCreateOption.DatabaseAndSchema ); }
Drop the DevExpress GridControl component from the Toolbox onto the main window and modify XAML as shown below:
<Window x:Class="DXGrid_BindingToXPODataSource.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"> <Grid> <dxg:GridControl Name="grid" AutoPopulateColumns="True"> <dxg:GridControl.View> <dxg:TableView Name="tableView1" /> </dxg:GridControl.View> </dxg:GridControl> </Grid> </Window>
Generate sample data and bind it to the grid:
public MainWindow() { InitDAL(); GenerateData(); InitializeComponent(); grid.ItemsSource = new XPCollection<ProductDataObject>(); } // Generates sample data if the "Product" database is empty. private void GenerateData() { if (Session.DefaultSession.FindObject<ProductDataObject>(null) != null) return; using (UnitOfWork uow = new UnitOfWork()) { ProductDataObject pdo1 = new ProductDataObject(uow) { ProductName = "Product A", UnitPrice = 99 }; ProductDataObject pdo2 = new ProductDataObject(uow) { ProductName = "Product B", UnitPrice = 199 }; uow.CommitChanges(); } }
Run the application. The image below shows the result.
See Also