I want to make a DataGrid
in WPF, where some of the cells will \"merge together\", if they are alike.
Example:
+---------+------+-----+
I have created a demo project on github.com
Output:
XAML Code: Grid with two columns and each containing a DataGrid
C# code - There are three classes to structure data. (Removed constructors to reduce code lines)
class Item
{
public Name {get;}
public Price {set;}
}
class Basket : List-
{
public Name {get;}
}
class BasketCollection : List
{
}
Code behind in MainWindow.cs - Populate data and assign to DataGrids.
public MainWindow()
{
InitializeComponent();
//// Get some data to show in View
var baskets = GetData();
int rowHeight = 20; //// itemDataGrid row height is 20 in xaml
//// Create a list of annonymous type with properties Name an RowHeight.
//// RowHeight = Height of one row * number of items in current basket.
var basketNameData = baskets.Select(x => new { Name = x.Name, RowHeight = rowHeight * x.Count });
//// Assign data to first DataGrid
basketNameDataGrid.ItemsSource = basketNameData.ToList();
//// Get list of all Items in all baskets and assign as ItemsSource to second datagrid
itemDataGrid.ItemsSource = baskets.SelectMany(basket => basket).ToList();
}
///
/// Gets some data to bind to view
///
/// Basket Collection
private BasketCollection GetData()
{
var baskets = new BasketCollection();
var fruitBasket = new Basket("Fruit");
fruitBasket.Add(new Item("Alphonso Mango", 80));
fruitBasket.Add(new Item("Nagpur Orange", 10));
fruitBasket.Add(new Item("Dragon Fruit", 50));
var vegetableBasket = new Basket("Vegetable");
vegetableBasket.Add(new Item("Brinjal", 5));
vegetableBasket.Add(new Item("Broccoli", 5));
vegetableBasket.Add(new Item("Onion", 3));
baskets.Add(fruitBasket);
baskets.Add(vegetableBasket);
return baskets;
}
Note: This solution do not actually merge cells, but create such visual effect.You may try this. Demo uses two DataGrid controls. The row height of first DataGrid is increased to create merged cell effect.
Alternative : ReoGrid is MS Excel compatible control which supports merge/unmerge cells feature like Excel. ReoGrid claims to be free and open source. It do not support Data Binding but it has support for DataTable.