Compartilhar via


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

This example shows how to filter data in a view.

Exemplo

To create a filter, define a method that provides the filtering logic. The method is used as a callback and accepts a parameter of type object. The following method returns all the Order objects with the filled property set to "No", filtering out the rest of the objects.

Public Function Contains(ByVal de As Object) As Boolean
    Dim order1 As Order = TryCast(de, Order)
    Return (order1.Filled Is "No")
End Function
public bool Contains(object de)
{
    Order order = de as Order;
    //Return members whose Orders have not been filled
    return(order.Filled== "No");
}

You can then apply the filter, as shown in the following example. In this example, myCollectionView is a ListCollectionView object.

myCollectionView.Filter = new Predicate<object>(Contains);

To undo filtering, you can set the Filter property to null:

myCollectionView.Filter = null;

For information about how to create or obtain a view, see Como: Obter o Modo de Exibição Padrão de uma Coleção de Dados. Para o exemplo completo, consulte classificação e filtragem de itens em uma amostra de visualização.

If your view object comes from a CollectionViewSource object, you apply filtering logic by setting an event handler for the Filter event. In the following example, listingDataView is an instance of CollectionViewSource.

listingDataView.Filter += new FilterEventHandler(ShowOnlyBargainsFilter);

The following shows the implementation of the example ShowOnlyBargainsFilter filter event handler. This event handler uses the Accepted property to filter out AuctionItem objects that have a CurrentPrice of $25 or greater.

private void ShowOnlyBargainsFilter(object sender, FilterEventArgs e)
{
    AuctionItem product = e.Item as AuctionItem;
    if (product != null)
    {
        // Filter out products with price 25 or above
        if (product.CurrentPrice < 25)
        {
            e.Accepted = true;
        }
        else
        {
            e.Accepted = false;
        }
    }
}

Consulte também

Tarefas

Como: Sort Data in a View

Referência

CanFilter

CustomFilter

Conceitos

Revisão de Associação de Dados

Outros recursos

Data Binding How-to Topics