Create Collection based Resource for data binding

image_pdfimage_print


   
  

<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.cs

using System;
using System.Collections;
using System.Windows;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void SortButton_Click(object sender, RoutedEventArgs args)
        {
            SortableCountries sortableCountries = (SortableCountries)(this.Resources["sortableCountries"]);

            ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(sortableCountries);

            lcv.CustomSort = new SortCountries();
        }
    }

    public class SortCountries : IComparer
    {
        public int Compare(object x, object y)
        {
            string stringX = x.ToString();
            string stringY = y.ToString();
            
            return stringX.CompareTo(stringY);

        }
    }

    public class SortableCountries : ObservableCollection<string>
    {
        public SortableCountries()
        {
            this.Add("C");
            this.Add("B");
            this.Add("A");
        }
    }
}