Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports C1.Silverlight.FlexGrid

Namespace GroupAggregates
	Partial Public Class MainPage
		Inherits UserControl
		Public Sub New()
			InitializeComponent()

			' populate Aggregate combobox
			Dim aggregates = New Aggregate() { Aggregate.None, Aggregate.Sum, Aggregate.Average, Aggregate.Maximum, Aggregate.Minimum, Aggregate.Count }
			For Each agg In aggregates
				_cmbAggregates.Items.Add(agg)
			Next agg
			_cmbAggregates.SelectedIndex = 1 ' Aggregate.Sum

			' build data source
			Dim view = Product.GetProducts(200)

			' set up grouping
			Dim gd = view.GroupDescriptions
			gd.Add(New PropertyGroupDescription("Total")) ' grand total group
			gd.Add(New PropertyGroupDescription("Line")) ' group by product line
			gd.Add(New PropertyGroupDescription("Color")) ' group by product color
			gd.Add(New PropertyGroupDescription("Price")) ' group by price range
			Dim pgdPrice = TryCast(gd(gd.Count - 1), PropertyGroupDescription)
			pgdPrice.Converter = New PriceRangeConverter()

			' assign data source to grid
			_flex.ItemsSource = view

			' provide choices in grid editors
			_flex.Columns("Line").ValueConverter = New ColumnValueConverter(Product.GetLines(), True)
			_flex.Columns("Color").ValueConverter = New ColumnValueConverter(Product.GetColors(), False)

			' needed to show aggregates
			_flex.AreRowGroupHeadersFrozen = False
		End Sub

		' apply new type of aggregate when user selects it from the combo
		Private Sub _cmbAggregates_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
			For Each s As String In "Price,Cost,Weight,Volume".Split(","c)
				_flex.Columns(s).GroupAggregate = CType(_cmbAggregates.SelectedItem, Aggregate)
			Next s
		End Sub
	End Class

	' converter used to group prices into ranges
	Friend Class PriceRangeConverter
		Implements IValueConverter
        Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
            If TypeOf value Is Double Then
                Dim p = CDbl(value)
                If p < 50 Then
                    Return "Low"
                End If
                If p < 100 Then
                    Return "Medium"
                End If
                If p < 500 Then
                    Return "High"
                End If
                Return "Very High"
            End If
            Return value
        End Function
        Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
            Throw New NotImplementedException()
        End Function
	End Class
End Namespace
