使用ComboBox更改CollectionViewSource过滤器

时间:2012-12-05 21:36:25

标签: c# wpf xaml collectionviewsource

我想知道如何使用ComboBox更新CollectionViewSource上的过滤器。 我有以下代码:

 <CollectionViewSource x:Key="cvsCars" 
                       Source="{Binding Source={StaticResource odpCars}}">
 <ComboBox Name="cbxMake" Margin="5" IsEnabled="False" />

我确定我需要为ComboBox提供某种SelectionChanged事件,但我无法找到使其能够使用此代码的方法。

private void MakeFilterOn(object sender, RoutedEventArgs e)
{
    cbxMake.IsEnabled = true;
    cvsCars.Filter += new FilterEventHandler(cvsCars_Filter);
}

void cvsCars_Filter(object sender, FilterEventArgs e)
{
    Car car = e.Item as Car;
    if (car != null)
    {
        if (car.Maker.ToString() == cbxMake.SelectedItem.ToString())
        {
            e.Accepted = true;
        }
        else
        {
            e.Accepted = false;
        }
    }
}

非常感谢任何建议。

CollectionViewSource填充了ObjectDataProvider。更新将应用于ListBox。 MakeFilterOn是一个CheckBox。

1 个答案:

答案 0 :(得分:2)

你必须刷新你的CollectionViewSource的视图...所以,在你的combobox的SelectionChanged事件的处理程序中,刷新你的cvs:

cvsCars.View.Refresh();

您可能希望了解WPF的数据绑定功能,然后再查看模型视图ViewModel(MVVM)“模式”。这样,您可以将组合框的SelectedItem绑定到窗口DataContext上的属性,并且无需处理SelectionChanged事件。