移动到CollectionViewSource中的特定项目?

时间:2016-01-06 13:42:27

标签: c# wpf entity-framework mvvm

我是WPF的新手,我正在尝试使用MVVM。我在我的视图模型中使用CollectionViewSource对使用Entity Framework的SQL数据库。

所以让我说我有这个课程:

>>> 'String with \n newline'
'String with \n newline'
>>> repr('String with \n newline')
"'String with \\n newline'"
>>> print repr('String with \n newline')
'String with \n newline'
>>> 'This will show the string in Python notation: %r' % ('String with \n newline',)
"This will show the string in Python notation: 'String with \\n newline'"
>>> print 'This will show the string in Python notation: %r' % ('String with \n newline',)
This will show the string in Python notation: 'String with \n newline'

让我们说这就是我在数据库中所拥有的:

ID:姓名:

  1. Bugs Bunny

  2. Mick Jagger

  3. 米老鼠

  4. 唐老鸭

  5. 高飞

  6. Elmer Fudd

  7. Daffy Duck

  8. Porky Pig

  9. 现在使用CollectionViewSource.View,我知道如何使用方法MoveCurrentToNext(),MoveCurrentToPrevious()等,并且工作正常,但我需要移动到一个特定的名称,例如唐老鸭。所以,如果我这样做:

    public class People
    {   
        public int Id { get; set; }
        public string name { get; set; }
    }
    

    或者如果我这样做

    dbContext.Peoples.Find(4);
    

    这将使用Entity Framework从数据库中获取正确的对象。但是,如果我这样做:

    dbContext.Peoples.Where(p => p.Name == "Donald Duck").FirstOrDefault();
    

    它不会移动,CollectionViewSource.View.CurrentItem为null。

    那么有人会如何移动到正确的项目?

1 个答案:

答案 0 :(得分:1)

我想这是因为您在调用dbContext.Peoples.Find(4)时获得的引用与您在CollectionView源代码集中的引用不同。

CollectionViewSource.View.MoveCurrentTo(其他' MoveTo' collectionView的方法)需要一个与源集合中的参数相同的参数。

然后,如果用于检索对象的dbContext方法返回的新实例或实例与CollectionView中的实例不同,则无法工作。

因此,要么使用中间集合作为集合视图的源来保持对对象的唯一引用(并在数据访问上下文中的对象发生更改时更新这些引用),要么尝试在{{1 class(从未尝试过后面的解决方案,但应该可以工作)。

此外,尝试在您的问题中添加一些完整的代码而不是代码片段,我们无法确切地看到问题的确切位置。