Apply Custom Sorting Logic to a Collection : ItemsControl « Windows Presentation Foundation « VB.Net Tutorial






<Window 
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="WPF" Height="300" Width="180">

    <Window.Resources>
        <local:SortableCountries x:Key="sortableCountries"/>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <ItemsControl ItemsSource="{StaticResource sortableCountries}" />
            <Button Click="SortButton_Click" Content="Sort" Margin="8" />
        </StackPanel>

    </Grid>

</Window>

//File:Window.xaml.vb

Imports System
Imports System.Collections
Imports System.Windows
Imports System.Windows.Data
Imports System.Collections.ObjectModel

Namespace WpfApplication1
  Public Partial Class Window1
    Inherits Window
    Public Sub New()
      InitializeComponent()
    End Sub

    Private Sub SortButton_Click(sender As Object, args As RoutedEventArgs)
      Dim sortableCountries As SortableCountries = DirectCast(Me.Resources("sortableCountries"), SortableCountries)

      Dim lcv As ListCollectionView = DirectCast(CollectionViewSource.GetDefaultView(sortableCountries), ListCollectionView)

      lcv.CustomSort = New SortCountries()
    End Sub
  End Class

  Public Class SortCountries
    Implements IComparer
    Public Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare
      Dim stringX As String = x.ToString()
      Dim stringY As String = y.ToString()

      Return stringX.CompareTo(stringY)

    End Function
  End Class

  Public Class SortableCountries
    Inherits ObservableCollection(Of String)
    Public Sub New()
      Me.Add("C")
      Me.Add("B")
      Me.Add("A")
    End Sub
  End Class
End Namespace
WPF Apply Custom Sorting Logic To A Collection








16.99.ItemsControl
16.99.1.Apply Custom Sorting Logic to a CollectionApply Custom Sorting Logic to a Collection
16.99.2.Bind an ItemsControl to the CollectionViewSource, Set its DisplayMemberPath to display the Name propertyBind an ItemsControl to the CollectionViewSource, Set its DisplayMemberPath to display the Name property
16.99.3.Sort Data in a CollectionSort Data in a Collection
16.99.4.Group Data in a CollectionGroup Data in a Collection