创建CustomControl的步骤我就不再累述,不清楚的请参考综合应用WPF/WCF/WF/LINQ之三:采用用代码创建的方式实现CheckListBox的CustomControl

  为了方便大家学习,请单击此处下载该程序的代码。
  这次Themes\SortableListView.xaml的内容为:
    1 <ResourceDictionary
    4    xmlns:local="clr-namespace:Eallies.OA.UI.Controls.Common">
    5
    6     <DataTemplate x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:SortableListView}, ResourceId=ColumnHeaderSortedAscendingTemplate}">
    7         <DockPanel>
    8             <TextBlock HorizontalAlignment="Center" Text="{Binding}" />
    9             <Path StrokeThickness="1" Fill="Gray" Data="M 5,10 L 15,10 L 10,5 L 5,10" />
   10         </DockPanel>
   11     </DataTemplate>
   12
   13     <DataTemplate x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:SortableListView}, ResourceId=ColumnHeaderSortedDescendingTemplate}">
   14         <DockPanel>
   15             <TextBlock HorizontalAlignment="Center" Text="{Binding}" />
   16             <Path StrokeThickness="1" Fill="Gray" Data="M 5,5 L 10,10 L 15,5 L 5,5" />
   17         </DockPanel>
   18     </DataTemplate>
   19
   20 </ResourceDictionary>
  这里,我们定义了两个DataTemplate,分别用于实现向上排序和向下排序的方向箭头。注意:这里的难点在于Key的命名,如果您采用常规的x:Key="ColumnHeaderSortedAscendingTemplate"的方式命名,您将不能在代码中找到该资源。
  之后,我们就可以很方便的用下面的方式找到该资源:
    1     ComponentResourceKey ascending = new ComponentResourceKey(typeof(SortableListView), "ColumnHeaderSortedAscendingTemplate");
    2     if (direction == ListSortDirection.Ascending) column.HeaderTemplate = this.TryFindResource(ascending) as DataTemplate;
  解决这个难点后,具体的排序代码就比较简单了,请大家参考源代码,网上也有大把的例子可以参考。
  现在让我们来看看页面中关于该控件的使用:
    1     <common:SortableListView Name="headLinesGridView" ItemsSource="{Binding}">
    2         <ListView.View>
    3             <GridView>
    4                 <common:SortableGridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" SortPropertyName="ID" Width="50" />
    5                 <common:SortableGridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" />
    6                 <common:SortableGridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" SortPropertyName="LastName" />
    7                 <common:SortableGridViewColumn Header="Date of Birth" DisplayMemberBinding="{Binding DateOfBirth}" SortPropertyName="DateOfBirth" IsDefaultSortColumn="True" />
    8             </GridView>
    9         </ListView.View>
   10     </common:SortableListView>
  可以看出,上面的XAML代码中没有引用任何有关排序的DataTemplate代码,但它却已经具备了排序的功能了。这样是不是让人感觉排序功能是“与生俱来”的呢?