如何创建 WPF ListCollectionView 来对 DataGrid CollectionViewSources 进行排序

发布于 2024-12-21 07:03:49 字数 4144 浏览 1 评论 0 原文

这是我的 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}}" />

我目前有以下控件相互提供数据:

我的窗口的 DataContext 通过容纳我所有控件的网格提供:

<Grid DataContext="{StaticResource topLevelAssysViewSource}">

一个组合框:

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

一个列表框:

<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" />

最后,一个我试图对其进行排序的 DataGrid -能够:(现在只有一列):

<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>

到目前为止,我的确切代码是:

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));
    }

我已经阅读并理解了创建 ListCollectionViews 的重要性,以便处理 CollectionViewSource 中包含的排序属性,这是我从博客 Bea Stollnitz 的博客

但是,我不断收到错误消息空引用异常未处理:“对象引用未设置到对象的实例。”

我该如何处理这个问题?我是否需要进一步定义我的ListCollectionView,或者我是否需要建立一个ICollectionView?我的 PartNum 列包含以数字开头(有时以字母开头)的部件号。标准排序方向适用吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

删除→记忆 2024-12-28 07:03:49

请提供异常的完整堆栈跟踪,或者至少提供示例中引发此异常的行数。

从您到目前为止提供的内容来看,我认为错误的根源是

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

如果您使用实体框架,则 ObjectQuery 结果的默认视图将不是 ListCollectionView,因此会出现 NullReferenceException。

要使用 ObjectQuery/EntityCollection 作为 CollectionViewSource 的源并使用它进行排序,您必须将其包装在支持排序的其他容器中(如果要执行 CRUD,请在各处使用该容器而不是源 EntityCollection)。

例如,尝试按照以下方式进行操作:

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();

并更改绑定以引用 CollectionViewSource.View 属性:

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

附加阅读:http://blog.nicktown.info/2008/12/10/using-a-collectionviewsource-to-display-a-sorted-entitycollection.aspx

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文