Compartilhar via


Como: Classificar dados na visualização

This example describes how to sort data in a view.

Exemplo

The following example creates a simple ListBox and a Button:

<Window x:Class="ListBoxSort_snip.Window1"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://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>

The Click event handler of the button contains logic to sort the items in the ListBox in the descending order. You can do this because adding items to a ListBox this way adds them to the ItemCollection of the ListBox, and ItemCollection derives from the CollectionView class. If you are binding your ListBox to a collection using the ItemsSource property, you can use the same technique to sort.

private void OnClick(object sender, RoutedEventArgs e)
{
    myListBox.Items.SortDescriptions.Add(
        new SortDescription("Content", ListSortDirection.Descending));
}

As long as you have a reference to the view object, you can use the same technique to sort the content of other collection views. For an example of how to obtain a view, see Como: Obter o Modo de Exibição Padrão de uma Coleção de Dados. For another example, see Como: Sort a GridView Column When a Header Is Clicked. For more information about views, see Binding to Collections in Revisão de Associação de Dados.

For an example of how to apply sorting logic in Extensible Application Markup Language (XAML), see Como: Ordenar e Agrupar Dados usando um modo de exibição em XAML.

Consulte também

Tarefas

Como: Sort a GridView Column When a Header Is Clicked

Como: Filtrar dados em um modo de exibição

Conceitos

Revisão de Associação de Dados

Referência

CustomSort

Outros recursos

Exemplos de ligação de dados

Data Binding How-to Topics