建立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代碼,但它卻已經具有了排序的功能了。這樣是否是讓人感受排序功能是「與生俱來」的呢?