How to create a WPF ListCollectionView to sort DataGrid CollectionViewSources

user1076406 picture user1076406 · Dec 14, 2011 · Viewed 7.9k times · Source

Here are my CollectionViewSources:

<CollectionViewSource x:Key="topLevelAssysViewSource" d:DesignSource="{d:DesignInstance my:TopLevelAssy, CreateList=True}" />
<CollectionViewSource x:Key="topLevelAssysRefPartNumsViewSource" Source="{Binding  Path=RefPartNums, Source={StaticResource topLevelAssysViewSource}}" />
<CollectionViewSource x:Key="topLevelAssysRefPartNumsRefPartNumBomsViewSource" Source="{Binding Path=RefPartNumBoms, Source={StaticResource topLevelAssysRefPartNumsViewSource}}" />

I currently have the following controls feeding data to one another:

DataContext for my window is fed through a Grid housing all of my Controls:

<Grid DataContext="{StaticResource topLevelAssysViewSource}">

A ComboBox:

<ComboBox DisplayMemberPath="TopLevelAssyNum" Height="23" HorizontalAlignment="Left"   ItemsSource="{Binding}" Margin="12,12,0,0" Name="topLevelAssysComboBox" SelectedValuePath="TopLevelAssyID" VerticalAlignment="Top" Width="120" />

a ListBox:

<ListBox DisplayMemberPath="RefPartNum1" Height="744" HorizontalAlignment="Left" ItemsSource="{Binding Source={StaticResource topLevelAssysRefPartNumsViewSource}}" Margin="12,41,0,0" Name="refPartNumsListBox" SelectedValuePath="RefPartNumID" VerticalAlignment="Top" Width="120" />

Finally, a DataGrid which I am trying to make Sort-able: (Just one Column for now):

<DataGrid CanUserSortColumns="true"  AutoGenerateColumns="False" EnableRowVirtualization="True" HorizontalAlignment="Left" ItemsSource="{Binding Source={StaticResource topLevelAssysRefPartNumsRefPartNumBomsViewSource}}" Margin="6,6,0,1" Name="refPartNumBomsDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Width="707">
    <DataGrid.Columns >
        <DataGridTextColumn x:Name="cageCodeColumn" Binding="{Binding Path=CageCode}" Header="CageCode" Width="45"  />
        <DataGridTextColumn x:Name="partNumColumn" Binding="{Binding Path=PartNum}" Header="PartNum" Width="165" SortDirection="Ascending" />
    </DataGrid.Columns>
</DataGrid>

My Exact code thus far is:

public partial class MainWindow : Window
{
    racr_dbEntities racr_dbEntities = new racr_dbEntities();

    public MainWindow()
    {
        InitializeComponent();
    }

    private System.Data.Objects.ObjectQuery<TopLevelAssy> GetTopLevelAssysQuery(racr_dbEntities racr_dbEntities)
    {
        // Auto generated code

        System.Data.Objects.ObjectQuery<racr_dbInterface.TopLevelAssy> topLevelAssysQuery = racr_dbEntities.TopLevelAssys;
        // Update the query to include RefPartNums data in TopLevelAssys. You can modify this code as needed.
        topLevelAssysQuery = topLevelAssysQuery.Include("RefPartNums");
        // Update the query to include RefPartNumBoms data in TopLevelAssys. You can modify this code as needed.
        topLevelAssysQuery = topLevelAssysQuery.Include("RefPartNums.RefPartNumBoms");
        // Returns an ObjectQuery.
        return topLevelAssysQuery;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Load data into TopLevelAssys. You can modify this code as needed.
        CollectionViewSource topLevelAssysViewSource = ((CollectionViewSource)(this.FindResource("topLevelAssysViewSource")));
        ObjectQuery<racr_dbInterface.TopLevelAssy> topLevelAssysQuery = this.GetTopLevelAssysQuery(racr_dbEntities);
        topLevelAssysViewSource.Source = topLevelAssysQuery.Execute(MergeOption.AppendOnly);

         ListCollectionView topLevelAssyView = CollectionViewSource.GetDefaultView(CollectionViewSource.CollectionViewTypeProperty) as ListCollectionView;
        topLevelAssyView.SortDescriptions.Add(new SortDescription("PartNum", ListSortDirection.Descending));
    }

I have read and understand the importance of creating the ListCollectionViews in order to handle the sort properties included in the CollectionViewSource, which I got from blog Bea Stollnitz's blog.

However, I keep getting the error message Null Reference Exception Unhandled: "Object reference not set to an instance of the object."

How do I take care of this issue? Do I need to further define my ListCollectionView, or perhaps I need to establish an ICollectionView? My PartNum column contains part numbers that begin with numbers and sometimes letters. Will the standard sortdirections apply?

Answer

surfen picture surfen · Dec 15, 2011

Please provide full stack trace for the exception, or at least number of line in your example which throws this exception.

From what you've provided so far, I think that the source of error is

ListCollectionView topLevelAssyView = CollectionViewSource.GetDefaultView(CollectionViewSource.CollectionViewTypeProperty) as ListCollectionView;

If you are using Entity Framework, the default View for ObjectQuery Results will not be ListCollectionView, hence NullReferenceException.

To use ObjectQuery/EntityCollection as the source for CollectionViewSource and sort with it you have to wrap it in some other container that supports sorting (and if want to perform CRUD, use that container everywhere instead of source EntityCollection).

For example, try something along those lines:

ObservableCollection<TopLevelAssy> observableCollection = new ObservableCollection(topLevelAssysQuery.Execute(MergeOption.AppendOnly));
((ISupportInitialize)topLevelAssysViewSource).BeginInit();
topLevelAssysViewSource.CollectionViewType = typeof(ListCollectionView);
topLevelAssysViewSource.Source = observableCollection;
topLevelAssysViewSource.SortDescriptions.Add(new SortDescription("CageCode", ListSortDirection.Ascending));
((ISupportInitialize)topLevelAssysViewSource).EndInit();

And change your binding to refer to CollectionViewSource.View property:

ItemsSource="{Binding Source={StaticResource topLevelAssysViewSource}, Path=View}"

Additional reading: http://blog.nicktown.info/2008/12/10/using-a-collectionviewsource-to-display-a-sorted-entitycollection.aspx