如何:排序檢視中的資料

此範例描述如何在檢視中排序資料。

範例

下列範例會建立簡單 ListBoxButton

<Window x:Class="ListBoxSort_snip.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ListBoxSort_snip" Height="300" Width="300">
    <DockPanel>
      <ListBox Name="myListBox" DockPanel.Dock="Top">
        <ListBoxItem>my</ListBoxItem>
        <!--Or you can set the content this way:-->
        <!--<ListBoxItem Content="my"/>-->
        <ListBoxItem>1</ListBoxItem>
        <ListBoxItem>Sort</ListBoxItem>
        <ListBoxItem>3</ListBoxItem>
        <ListBoxItem>ListBox</ListBoxItem>
        <ListBoxItem>2</ListBoxItem>
      </ListBox>
      <Button Click="OnClick" Width="30" Height="20" DockPanel.Dock="Top">Sort</Button>
    </DockPanel>
</Window>

按鈕 Click 的事件處理常式包含邏輯,以遞減順序排序 中的專案 ListBox 。 您可以這麼做,因為將專案加入至 ,因此會將專案 ListBox 新增至 ItemCollectionListBox ,並 ItemCollection 衍生自 CollectionView 類別。 如果您要使用 ItemsSource 屬性將 系 ListBox 結至集合,您可以使用相同的技術來排序。

private void OnClick(object sender, RoutedEventArgs e)
{
    myListBox.Items.SortDescriptions.Add(
        new SortDescription("Content", ListSortDirection.Descending));
}
Private Sub OnClick(ByVal sender As Object, ByVal e As RoutedEventArgs)
    myListBox.Items.SortDescriptions.Add(New SortDescription("Content", ListSortDirection.Descending))
End Sub

只要您有檢視物件的參考,就可以使用相同的技術來排序其他集合檢視的內容。 如需如何取得檢視的範例,請參閱 取得資料收集 的預設檢視。 如需另一個範例,請參閱 按一下 標頭時排序 GridView 資料行。 如需檢視的詳細資訊,請參閱在資料系結概觀 系結至集合。

如需如何在可延伸應用程式標記語言中套用排序邏輯的範例,請參閱 使用 XAML 中的檢視來排序和分組資料。

另請參閱