Imports C1.Silverlight.Maps
Imports System.IO
Imports System.Reflection
Imports VectorLayer.VectorLayer
Imports System.Windows.Data
Imports System.Globalization

Partial Public Class Cities
    Inherits UserControl
    Private vl As C1VectorLayer

    Public Sub New()
        InitializeComponent()

        AddHandler Me.Loaded, AddressOf Cities_Loaded
        AddHandler Me.Unloaded, AddressOf Cities_Unloaded
    End Sub

    Private Sub Cities_Unloaded(sender As Object, e As RoutedEventArgs)
        'Release memory
        If vl IsNot Nothing Then
            For Each child As C1VectorPlacemark In vl.Children
                Dim place = TryCast(child, C1VectorPlacemark)
                If place IsNot Nothing Then
                    RemoveHandler place.Loaded, AddressOf C1VectorPlacemark_Loaded
                End If
            Next
        End If

        vl = Nothing
    End Sub
    Private Sub Cities_Loaded(sender As Object, e As RoutedEventArgs)
        Dim fc As Color = Color.FromArgb(&HFF, &HC0, &H50, &H4D)
        maps.Foreground = New SolidColorBrush(fc)

        vl = New C1VectorLayer()

        Dim resource = Application.GetResourceStream(New Uri("/" + New AssemblyName(Assembly.GetExecutingAssembly().FullName).Name + ";component/Resources/Cities100K.txt", UriKind.Relative))
        Dim stream As Stream = resource.Stream
        If stream IsNot Nothing Then
            Dim cities As List(Of City) = City.Read(stream)
            vl.ItemTemplate = DirectCast(Resources("templCity"), DataTemplate)
            Dim source As IEnumerable(Of City) = From c In cities Order By c.Population Descending Select c
            vl.ItemsSource = source.Take(500)
        End If
        maps.Layers.Add(vl)
    End Sub

    Private Sub C1VectorPlacemark_Loaded(sender As Object, e As RoutedEventArgs)
        Dim pl As C1VectorPlacemark = DirectCast(sender, C1VectorPlacemark)
        Dim city As City = DirectCast(pl.DataContext, City)
        ToolTipService.SetToolTip(pl, city.Name + ":" & vbLf & city.Population.ToString())
    End Sub
End Class


