GridControl: Conditional data binding

Wpf GridControl provides new data binding engines in addition to existing:

  • Binding to multiple sources
  • Declarative hierarchical binding based on hierarchy fields of data objects
  • Binding on any hierarchy level with Row.ItemsSource
  • Conditional binding

Conditional binding is one of the most powerful and convenient binding types. API provided by the grid that enables the programmer to specify insertion method when a data object is added to the grid.

Wpf GridControl conditional binding

This API is implemented as an event that is called when data is added to the grid: GridControl.RowAdding The event GridControlRowAddingEventArgs contains a reference to the added object, a parent row if any and insertion method for this object. Below is the list of possible actions upon data insertion to the grid:

  • AsChild – regular method of data object insertion to parent. A programmer may replace the inserted object with any other object on his own discretion.
  • AsCollection – a programmer may replace a data object with any collection that shall be added instead of the specified object. If the inserted basket contains multiple orders, the grid shall skip the basket and add a collection instead.
  • AsChildAndCollection – the grid adds a data object and a new collection. The data object is added to the specified parent as with AsChild, and the collection is added to the newly added data object on the next hierarchy level.
  • Skip – the data object is not added to the grid

It is important to note that if a collection implements IBindingList interface, the grid subscribes to events of this collection and inserts or modifies data on corresponding hierarchy level of the grid. All binding list operations are thread safe.

//Basket class
public class Basket 
{
    //Private fields
    private readonly BindingList<Order> _orders = new BindingList<Order>();

    //Public properties    
    public IList<Order> Orders
    {
        get { return _orders; }
    }
}

//Initialize the grid
public void InitializeGrid(GridControl grid, IList<Basket> baskets)
{
    grid.RowAdding += OnGridRowAdding;

    //Bind the grid to basket collection
    grid.ItemsSource = baskets;
}


private void OnGridRowAdding(object sender, GridControlRowAddingEventArgs e)
{
    //Skip the 'basket' level and bind orders directly to basket's parent
    Basket basket = e.DataObject as Basket;
    if (basket != null)
    {
        e.DataObject = basket.Orders;
        e.InsertionType = InsertionType.AsCollection;
    }
}

Back to Wpf GridControl features