Bind to Local Data

  • 2 minutes to read

This topic demonstrates how to bind the GridControl to a local database:

  1. Connect your project to a local database.

  2. Create a ViewModel:

    using DevExpress.Mvvm;
    using System.Collections.ObjectModel;
    using System.Data.Entity;
    
    namespace DXGridGetStarted {
        public class ViewModel : ViewModelBase {
            NorthwindEntities northwindDBContext;
            public ViewModel() {
                if (IsInDesignMode) {
                    Orders = new ObservableCollection<Order>();
                } 
                else {
                    northwindDBContext = new NorthwindEntities();
    
                    northwindDBContext.Orders.Load();
                    Orders = northwindDBContext.Orders.Local;
                }
            }
            public ObservableCollection<Order> Orders {
                get => GetValue<ObservableCollection<Order>>();
                private set => SetValue(value);
            }
        }
    }
    
    NOTE

    To use the Order object's properties at design time without a direct database connection, add an empty Orders collection to the ViewModel.

  3. Build the solution to make the ViewModel class visible in the window's smart tag DataContext menu.

  4. Open the ThemedWindow's smart tag menu and define the window's data context:

    You can also define the window's data context in code:

    <dx:ThemedWindow
        ...
        xmlns:local="clr-namespace:DXGridGetStarted">
        <dx:ThemedWindow.DataContext>
            <local:ViewModel/>
        </dx:ThemedWindow.DataContext>
    
  5. Open the GridControl's smart tag menu and specify the ItemsSource:

    To bind the GridControl to data in code, specify the DataControlBase.ItemsSource property:

    <dxg:GridControl AutoGenerateColumns="AddNew"
                     EnableSmartColumnsGeneration="True"
                     ItemsSource="{Binding Orders}">
        <dxg:GridControl.View>
            <dxg:TableView ShowTotalSummary="True"/>
        </dxg:GridControl.View>
    </dxg:GridControl>
    
  6. Run the project. The GridControl generates columns for all fields from a bound data source:

NOTE

For information on how to post changes to a database, refer to the following help topic: Post Changes to a Database.

GitHub Examples

Framework GitHub link
.NET Framework View Example: WPF Data Grid - Getting Started
.NET Core View Example: WPF Data Grid - Getting Started .NET Core
See Also