Tuesday, 27 November 2012

Sorting PivotViewer Silverlight5

There is a sort property on the PivotViewerProperty but that’s used to sort the filter on the left hand side of the page (see sector is sorted by quantity, then A-Z on sector).

To sort within a group you need to implement an IComparable interface on an aggregate property.  Here’s what I mean:

image

You’ll see this data is “sorted” by Sector, which actually groups but within each group the data is sorted by coupon (the big number in the middle).  Here’s how I did it:

private string sector;
public string Sector
{
get { return sector; }
set { sector = value; NotifyProperty("Sector"); }
}

private ValueSortByCoupon sectorSort;
public ValueSortByCoupon SectorSort
{
get { return sectorSort ?? (sectorSort = new ValueSortByCoupon(Sector, CouponToday)); }
}

....

public class ValueSortByCoupon : IComparable
{
private string Value { get; set; }
private decimal Coupon { get; set; }

public ValueSortByCoupon(string sector, decimal coupon)
{
this.Value = sector;
this.Coupon = coupon;
}

public int CompareTo(object rhs)
{
var other = (ValueSortByCoupon)rhs;
var result = this.Value == other.Value
? other.Coupon.CompareTo(this.Coupon)
: this.Value.CompareTo(other.Value);
return result;
}

public override string ToString()
{
return Value;
}
}
<pivot:PivotViewer>
<pivot:PivotViewer.PivotProperties>
<pivot:PivotViewerStringProperty Id="SectorSort"
DisplayName="Sector"
Options="CanFilter,CanSearchText"
Binding="{Binding SectorSort, Mode=OneWay}" />
</pivot:PivotViewer.PivotProperties>
</pivot:PivotViewer>

Source:  http://github.com/stevenh77/pivotviewerdemo

2 comments:

  1. Wouldn't a Linq expression be an easier way to do this? Or is the object in question not viable for Linq?

    ReplyDelete