3

我不知道为什么我的 ICollectionView 没有刷新。谁能解释我做错了什么?

我制作了这样的视图模型:

class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Entity> m_entities = new ObservableCollection<Entity>();
    public ICollectionView EntitiesView { get; private set; }
    public ICollectionView HighCountView { get; private set; }

    public ViewModel()
    {
        m_entities.Add(new Entity() { Id = 1, Name = "Erik", Description = "The first" });
        m_entities.Add(new Entity() { Id = 2, Name = "Olle", Description = "The second" });
        m_entities.Add(new Entity() { Id = 3, Name = "Kim", Description = "The last" });


        EntitiesView = CollectionViewSource.GetDefaultView(m_entities);
        EntitiesView.CurrentChanged += new EventHandler(EntitiesView_CurrentChanged);

        HighCountView = new CollectionView(m_entities);
        using (HighCountView.DeferRefresh())
        {
            HighCountView.Filter = e => ((Entity)e).Count > 3;
        }

    }

    private void EntitiesView_CurrentChanged(object sender, EventArgs e)
    {
        Entity current = EntitiesView.CurrentItem as Entity;
        if(current!=null)
        {
            current.Count++;
            HighCountView.Refresh();            // Do I need this line?
            OnPropertyChanged("HighCountView"); // or this?
        }
    }

...在我的窗口中,我将其用作数据上下文,如下所示:

public partial class MainWindow : Window
{
    private ViewModel vm = new ViewModel();
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.DataContext = vm;
    }
}

...我正在像这样在 XAML 代码中进行绑定:

    <ListBox Grid.Column="0" x:Name="listView1" DisplayMemberPath="Name" ItemsSource="{Binding EntitiesView}" IsSynchronizedWithCurrentItem="True" />
    <ListView Grid.Column="1" x:Name="listView2" DisplayMemberPath="Name" ItemsSource="{Binding HighCountView}" IsSynchronizedWithCurrentItem="True" />

问题是所有三个实体始终显示在 listView2 中,尽管我设置了过滤器属性。为什么?

编辑

为了使示例完整,这里是实体类。

class Entity : INotifyPropertyChanged
{
    private int m_id;
    public int Id
    {
        bla bla.....
    }

    private string m_name;
    public string Name
    {
        bla bla.....
    }

    private string m_description;
    public string Description
    {
        bla bla.....
    }


    private int m_count;
    public int Count
    {
        get { return m_count; }
        set
        {
            if (value != m_count)
            {
                m_count = value;
                OnPropertyChanged("Count");
            }
        }
    }

    public void Update()
    {
        Description = "Updated: " + (++Count).ToString() + " times.";
    }
4

1 回答 1

4

最后我发现了问题所在。

如果我换行:

    HighCountView = new CollectionView(m_entities);

对此

    HighCountView = new ListCollectionView(m_entities);

然后它按预期工作。

我也可以删除这条线

        OnPropertyChanged("HighCountView"); // or this?

我希望这可以帮助别人!

于 2012-10-29T06:28:13.957 回答