Search code examples
c#wpfsqlitexamllistcollectionview

datagrid customsorting BindingListCollectionView to type ListCollectionView error


So i'm trying to learn wpf and recoding a c# .net forms project to wpf. at the same time i'm trying to fix issues that i had with the forms project. one of which is column not sorting correctly. there is a column that is alphanumeric for "filenames" primary column. i found a package that i thought would work DataGrid CustomSorting but in use case it errors out and i don't know if its caused by how i'm binding to datagrid or what. the project doesn't have much documentation.

the line of code erroring out

var listCollectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);

the error

'Unable to cast object of type 'System.Windows.Data.BindingListCollectionView' to type 'System.Windows.Data.ListCollectionView'.'

Full block of code

private static void HandleCustomSorting(object sender, DataGridSortingEventArgs e)
        {
            var dataGrid = (DataGrid)sender;

            if (!GetUseCustomSort(dataGrid))
            {
                return;
            }

            if (string.IsNullOrEmpty(e.Column.SortMemberPath))
            {
                return;
            }

            var listCollectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
            IComparer sorter = GetCustomSorter(e.Column);

            if (sorter == null)
            {
                return;
            }

            listCollectionView.CustomSort = new ColumnComparer(sorter, e.Column);

            e.Handled = true;
        }

loading datagrid

private void PricingActiveCatagory_SelectedIndexChanged(object sender, EventArgs e)
        {
            string Dir1 = string.Format("{0}/Displays/{1}/{2}", SV.appPath, PricingActiveDisplay.SelectedValue.ToString(), PricingActiveCatagory.SelectedItem.ToString());
            string[] fileList1 = Directory.GetFiles(Dir1);
            if (fileList1.Length > 0)
            {
                var conn = new SQLiteConnection(string.Format("data source ={0}/database/{1}.sqlite;Version=3;New=True;Compress=True;", SV.appPath, PricingActiveDisplay.SelectedValue.ToString()));
                dt.Clear();
                dt.Columns.Clear();
                dt = new DataTable();
                try
                {
                    SQLiteCommandBuilder builder = new SQLiteCommandBuilder(da);
                    using (conn)
                    {
                        conn.Open();
                        dt.Rows.Clear();
                        if (Sqlite.TableExists(PricingActiveCatagory.SelectedItem.ToString(), conn))
                        {
                            var sql = ("SELECT * FROM \"" + PricingActiveCatagory.SelectedItem.ToString() + "\"");
                            using (SQLiteCommand cmdDataGrid = new SQLiteCommand(sql, conn))
                            {
                                da.SelectCommand = cmdDataGrid;
                                da.Fill(dt);
                                Pricing_view.DataContext = dt.DefaultView;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }

            }
        }

xaml datagrid

<DataGrid Grid.Row="1" Name="Pricing_view" AutoGenerateColumns="false" local:DataGridHelpers.UseCustomSort="True" ItemsSource="{Binding}"  >
                                    <DataGrid.Columns>
                                        <DataGridTextColumn  Binding="{Binding Filename}"  Header="File Name" SortDirection="Ascending" local:DataGridHelpers.CustomSorterType="{x:Type local:StrLogicalComparer}">
                                            <DataGridTextColumn.ElementStyle>
                                                <Style TargetType="TextBlock">
                                                    <Setter Property="HorizontalAlignment" Value="Center" />
                                                </Style>
                                            </DataGridTextColumn.ElementStyle>
                                        </DataGridTextColumn>
                                        <DataGridTextColumn  Binding="{Binding FileTimeStamp}"  Header="File Time Stamp"/>
                                        <DataGridTextColumn  Binding="{Binding dir}" Header="image Dir"/>
                                        <DataGridTextColumn  Binding="{Binding upc}"  Header="Upc Dir"/>
                                        <DataGridTextColumn  Binding="{Binding price}"  Header="Price"/>
                                    </DataGrid.Columns>
                                </DataGrid>

Any assistants is greatly appreciated the reason im trying to setup custom sort


Solution

  • If you want custom sorting with full control without any future error, I suggest just bind the datamodel but not viewsource,try it with remove all datasources and Resources to viewmodel from .xaml, create custom function for GettingSortedData(), LoadingSortedDataInDatagrid() with event handler