Considering the popularity of MVVM pattern with WPF, developers are always looking to implement every possible feature in XAML. In this small example, we have provided implementation to show Sorting and Grouping on C1Flexgrid for WPF using XAML. Core concept behind this implementation defines a CollectionViewSource object in XAML instead of code behind.
Create Collection Object
public class CustomerViewModel
{
private ObservableCollection _customerList;
public CustomerViewModel()
{
_customerList = new ObservableCollection();
_customerList.Add(new Customer() { Name = "John", Age = 29, City = "NewYork" });
_customerList.Add(new Customer() { Name = "Ram", Age = 25, City = "New Delhi" });
_customerList.Add(new Customer() { Name = "Xiang", Age = 39, City = "Tokyo" });
_customerList.Add(new Customer() { Name = "Dave", Age = 27, City = "Washington D.C." });
_customerList.Add(new Customer() { Name = "Allen", Age = 32, City = "London" });
_customerList.Add(new Customer() { Name = "Mark", Age = 30, City = "Canberra" });
_customerList.Add(new Customer() { Name = "David", Age = 26, City = "Pittsburgh" });
_customerList.Add(new Customer() { Name = "Sheila", Age = 25, City = "New Delhi" });
}
public ObservableCollection CustomerList
{
get { return _customerList; }
}
private string _sortField;
public string SortField
{
get{ return _sortField;}
set {_sortField=value;}
}
}
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
Define CollectionViewSource in XAML
Once we define the CollectionViewSource object in XAML, we have to set the SortDescription and GroupDescription properties.
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
<Window.Resources>
<CollectionViewSource x:Key="SortedItems" Source="{Binding Path=CustomerList}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="City" Direction="Descending"/>
</CollectionViewSource.SortDescriptions>
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="City"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Window.Resources>
Binding C1FlexGrid to CollectionViewSource
You would have noticed in the above code snippet, that we provided a Key to CollectionViewSource object. This would help us to set this CollectionViewSource as StaticResource object for ItemSource proprety of C1FlexGrid.
<c1:C1FlexGrid Name="c1FlexGrid1" AutoGenerateColumns="False" ItemsSource="{Binding Source={StaticResource SortedItems}}">
<c1:C1FlexGrid.Columns>
<c1:Column Binding="{Binding Name}"/>
<c1:Column Binding="{Binding Age}"/>
<c1:Column Binding="{Binding City}"/>
</c1:C1FlexGrid.Columns>
</c1:C1FlexGrid>