使用CollectionViewSource过滤ObservableCollection

时间:2016-01-29 18:25:34

标签: c# wpf mvvm

我有一个可观察的对象集合,会随着时间的推移而改变。

ObservableCollection
    Object 1
    Object 2
    ...

我想要做的是在组合框中显示此信息的过滤版本。所以我设置了一个CollectionViewSource,其源代码是ObservableCollection。我已经定义了谁的过滤器:

private const string Unknown = "Unknown";
public DevicePackageInfo()
{
    this.operatingSystemVersion = DevicePackageInfo.Unknown;
    this.packageVersionInfo = new PackageVersionInfo(DevicePackageInfo.Unknown);
    this.PackageVersionList = new ObservableCollection<PackageVersionInfo>() { new PackageVersionInfo(DevicePackageInfo.Unknown) };
    this.packageVersionCollectionView = new CollectionViewSource();
    this.packageVersionCollectionView.Filter += PackageHistoryFilter;
    this.packageVersionCollectionView.Source = this.PackageVersionList;

    this.SetSynced();
}

public void PackageHistoryFilter(object sender, FilterEventArgs e)
{
    if (e.Item != null)
        e.Accepted = ((PackageVersionInfo)e.Item).OnEAC || ((PackageVersionInfo)e.Item).SelectedOnPC;
}

问题是当我更新ObservableCollection时,我的组合框没有更新。

我在列表中看到的唯一对象是&#34;未知,&#34;在构建类时我添加到列表中的第一个对象。

我的解决方案可能不完全正确......但我感到困惑。是否有内置的方法可以让过滤的收集源从ObservableCollection订阅并保持最新状态?我该怎么做?

当我更改我的ObservableCollection时,我想更新绑定到我的组合框的集合。

最小代码是理想的,我真的不想定义一个实现通知等的新集合类。

编辑:这是我的XAML

<ComboBox  Name="cbSelection" bhvr:SelectionChangedBehaviour.Command="{Binding PackageSelectionCommand}" ItemsSource="{Binding PackageInfo.PackageVersionCollectionView.View, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding PackageInfo.PackageVersionInfo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  
                              IsSynchronizedWithCurrentItem="True">

1 个答案:

答案 0 :(得分:0)

我写了这篇文章,以便人们可以了解解决方案的样子:

public ObservableCollection<Tuple<String, String>> MyObservableCollection;
public CollectionViewSource MyCollectionViewSource { get; set; }

public PetViewModel()
{
    this.MyObservableCollection = new ObservableCollection<Tuple<String, String>>();
    this.MyCollectionViewSource = new CollectionViewSource();
    this.MyCollectionViewSource.Source = this.MyObservableCollection;
    this.MyCollectionViewSource.Filter += OnlyCatsFilter;

    this.MyObservableCollection.Add(new Tuple<string,string>("Paul", "Cat"));
    this.MyObservableCollection.Add(new Tuple<string,string>("Zoey", "Dog"));
    this.MyObservableCollection.Add(new Tuple<string,string>("Dude", "Turtle"));

    this.MyCollectionViewSource.View.Refresh();
}

public void OnlyCatsFilter(object sender, FilterEventArgs e)
{
    if (e.Item != null)
    {
        e.Accepted = (e.Item as Tuple<String, String>).Item2 == "Cat";
    }
}