gpt4 book ai didi

wpf - 为什么不刷新 ICollectionView?

转载 作者:行者123 更新时间:2023-12-04 23:45:30 26 4
gpt4 key购买 nike

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

我做了这样一个 View 模型:

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 代码中进行绑定(bind):

    <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.";
}

最佳答案

终于找到问题了

如果我改变行:

    HighCountView = new CollectionView(m_entities);

对此

    HighCountView = new ListCollectionView(m_entities);

然后它按预期工作。

我也可以删除这一行

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

希望对大家有所帮助!

关于wpf - 为什么不刷新 ICollectionView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12912057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com