Apply Custom Sorting Logic to a Collection


   
  

<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");
        }
    }
}

   
    
     


Bind to ObservableCollection and ItemsSource


   
  

<Window x:Class="DataTriggerSample.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:DataTriggerSample"
  Title="DataTriggerSample" Height="300" Width="300">
  <Window.Resources>
    <c:People x:Key="PeopleData"/>

    <Style TargetType="{x:Type ListBoxItem}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=Name}" Value="A">
          <Setter Property="Background" Value="Yellow" />
        </DataTrigger>
        <MultiDataTrigger>
          <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding Path=Name}" Value="S" />
          </MultiDataTrigger.Conditions>
          <MultiDataTrigger.Setters>
            <Setter Property="Background" Value="LightGreen" />
          </MultiDataTrigger.Setters>
        </MultiDataTrigger>
      </Style.Triggers>
    </Style>

    <DataTemplate DataType="{x:Type c:Person}">
      <Canvas Width="260" Height="20">
        <TextBlock FontSize="12" Width="130" Canvas.Left="0" Text="{Binding Path=Name}"/>
      </Canvas>
    </DataTemplate>
  </Window.Resources>

  <StackPanel>
    <TextBlock FontSize="18" Margin="5" FontWeight="Bold"
      HorizontalAlignment="Center">Data Trigger Sample</TextBlock>
    <ListBox Width="250" HorizontalAlignment="Center" Background="White"
      ItemsSource="{Binding Source={StaticResource PeopleData}}"/>
  </StackPanel>

</Window>
//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace DataTriggerSample
{
    public partial class Window1 : System.Windows.Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }

    public class Person
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Person(string name)
        {
            this._name = name;
        }
    }

    public class People : ObservableCollection<Person>
    {
        public People()
        {
            Add(new Person("A"));
            Add(new Person("B"));
            Add(new Person("C"));
        }
    }

}

   
    
     


Create a ListView control that uses a GridView view mode to display the contents of an ObservableCollection<(Of <(T>)>).

)>)." src="http://international.us.server12.fileserver.kutayzorlu.com/files/download/2011/05/WPF-CreateAListViewControlThatUsesAGridViewViewModeToDisplayTheContentsOfAnObservableCollectionOfT.PNG">

   
  


<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Loaded="OnLoad" xmlns:ds="clr-namespace:WpfApplication1">
 
  <Window.Resources>
    <ObjectDataProvider x:Key="EmployeeInfoDataSource" ObjectType="{x:Type ds:myEmployees}"/>
  </Window.Resources>
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="50"/>
      <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition/>
      <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Row="0" Grid.Column="0" FontSize="14" HorizontalAlignment="Center">
      ListView created with XAML
    </TextBlock>
    <StackPanel Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center">
      <ListView ItemsSource="{Binding Source={StaticResource EmployeeInfoDataSource}}">
        <ListView.View>
          <GridView AllowsColumnReorder="true" ColumnHeaderToolTip="Employee Information">
            <GridViewColumn DisplayMemberBinding= "{Binding Path=FirstName}" Header="First Name" Width="100"/>
            <GridViewColumn DisplayMemberBinding="{Binding Path=EmployeeNumber}" Header="Employee No." Width="100"/>
          </GridView>
        </ListView.View>
      </ListView>
    </StackPanel>
    <StackPanel Grid.Row="1" Grid.Column="1"  Name="myStackPanel" HorizontalAlignment="Center">
    </StackPanel>
  </Grid>
</Window>
//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;


namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        void OnLoad(object sender, RoutedEventArgs e)
        {
            ListView myListView = new ListView();
 
            GridView myGridView = new GridView();
            myGridView.AllowsColumnReorder = true; 
            myGridView.ColumnHeaderToolTip = "Employee Information";
 
            GridViewColumn gvc1 = new GridViewColumn();
            gvc1.DisplayMemberBinding = new Binding("FirstName");
            gvc1.Header = "FirstName";
            gvc1.Width = 100;
            myGridView.Columns.Add(gvc1);

            GridViewColumn gvc3 = new GridViewColumn();
            gvc3.DisplayMemberBinding = new Binding("EmployeeNumber");
            gvc3.Header = "Employee No.";
            gvc3.Width = 100;
            myGridView.Columns.Add(gvc3);

            myListView.ItemsSource = new myEmployees();
            myListView.View = myGridView;
            myStackPanel.Children.Add(myListView);
        }
    }

    public class EmployeeInfo
    {
        private string _firstName;
        private string _employeeNumber;

        public string FirstName
        {
            get {return _firstName;}
            set {_firstName = value;}
        }
        public string EmployeeNumber
        {
            get {return _employeeNumber;}
            set {_employeeNumber = value;}
        }

        public EmployeeInfo(string firstname, string empnumber)
        {
            _firstName = firstname;
            _employeeNumber = empnumber;
        }
    }
    public class myEmployees : ObservableCollection<EmployeeInfo>
    {
        public myEmployees()
        {
            Add(new EmployeeInfo("A",  "1"));
            Add(new EmployeeInfo("B",  "9"));
            Add(new EmployeeInfo("C",  "2"));
            Add(new EmployeeInfo("D",  "4"));
        }
    }
}

   
    
     


Bind to ObservableCollection


   
  
<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="HierarchicalBinding" xmlns:local="clr-namespace:WpfApplication1">
  <Window.Resources>
    <local:Companies x:Key="Companies">
      <local:Company CompanyName="CompanyA">
        <local:Company.Members>
          <local:People>
            <local:Employee Name="EmployeeA" Age="21">
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment1" />
                  <local:Comment Description="Comment2" />
                  <local:Comment Description="Comment3" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
            <local:Employee Name="Moe" Age="22" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Nice" />
                  <local:Comment Description="Comment3" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
            <local:Employee Name="Curly" Age="23" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment6" />
                  <local:Comment Description="Comment3" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
          </local:People>
        </local:Company.Members>
      </local:Company>
      <local:Company CompanyName="CompanyB">
        <local:Company.Members>
          <local:People>
            <local:Employee Name="EmployeeB" Age="135" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Rich" />
                  <local:Comment Description="Comment7" />
                  <local:Comment Description="Comment5" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
            <local:Employee Name="EmployeeC" Age="121" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment8" />
                  <local:Comment Description="Pale" />
                  <local:Comment Description="Comment4" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
            <local:Employee Name="EmployeeD" Age="137" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment8" />
                  <local:Comment Description="Comment6" />
                  <local:Comment Description="Comment3" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
          </local:People>
        </local:Company.Members>
      </local:Company>
    </local:Companies>

    <HierarchicalDataTemplate DataType="{x:Type local:Company}"
      ItemsSource="{Binding Path=Members}">
      <TextBlock Text="{Binding Path=CompanyName}" />
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="{x:Type local:Employee}"
      ItemsSource="{Binding Path=Comments}">
      <TextBlock>
        <TextBlock Text="{Binding Path=Name}" />
        (age: <TextBlock Text="{Binding Path=Age}" />)
      </TextBlock>
    </HierarchicalDataTemplate>

    <DataTemplate DataType="{x:Type local:Comment}">
      <TextBlock Text="{Binding Path=Description}" />
    </DataTemplate>

  </Window.Resources>

  <TreeView DataContext="{StaticResource Companies}">
    <TreeViewItem ItemsSource="{Binding}" Header="Companies" />
  </TreeView>
</Window>

//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Collections.ObjectModel;


namespace WpfApplication1 {

  public class Comment {
    string description;
    public string Description {
      get { return description; }
      set { description = value; }
    }
  }

  public class Comments : ObservableCollection<Comment> { }

  public class Employee {
    string name;
    public string Name {
      get { return name; }
      set { name = value; }
    }

    int age;
    public int Age {
      get { return age; }
      set { age = value; }
    }

    Comments traits;
    public Comments Comments {
      get { return traits; }
      set { traits = value; }
    }
  }

  public class People : ObservableCollection<Employee> { }

  public class Company {
    string familyName;
    public string CompanyName {
      get { return familyName; }
      set { familyName = value; }
    }

    People members;
    public People Members {
      get { return members; }
      set { members = value; }
    }
  }

  public class Companies : ObservableCollection<Company> { }

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