다음을 통해 공유


How to: Get the Default View of a Data Collection

Views allow the same data collection to be viewed in different ways, depending on sorting or filtering. Views also provide a current record pointer concept and enable moving the pointer. This example shows how to create a view object.

Example

To create the view, you need an object reference to the original data object. This data object can be obtained by referencing your own code-behind object, by getting the data context, by getting a property of the data source, or by getting a property of the binding. This example shows how to get the DataContext of a data object and use it to directly obtain the associated CollectionView. The GetDefaultView method is used to obtain the default collection view of the root element.

myCollectionView = (CollectionView)
    CollectionViewSource.GetDefaultView(rootElem.DataContext);

In this example, the root element is a StackPanel. The DataContext is set to myDataSource, which refers to a data provider that is an ObservableCollection of Order objects.

<StackPanel.DataContext>
  <Binding Source="{StaticResource myDataSource}"/>
</StackPanel.DataContext>

Alternatively, you can instantiate a view object directly using the CollectionViewSource class. For an example, see the How to Create a View section in the Data Binding Overview.

For examples of the functionality provided by a collection view, see How to: Sort Data in View, How to: Filter Data in a View, and How to: Navigate Through the Objects in a Data CollectionView.

See Also

Tasks

How to: Sort and Group Data Using a View in XAML

Other Resources

Data Binding Samples
Data Binding How-to Topics