2013-05-04 114 views
0

我有一个ObservableCollection的字符串,我打算将它与转换器绑定到ListBox并只显示以某些前缀开头的字符串。
我写道:WPF绑定ObservableCollection与转换器

public ObservableCollection<string> Names { get; set; } 

public MainWindow() 
{ 
    InitializeComponent(); 
    Names= new ObservableCollection<Names>(); 
    DataContext = this; 
} 

和转换器:

class NamesListConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value == null) 
      return null; 
     return (value as ICollection<string>).Where((x) => x.StartsWith("A")); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return null; 
    } 
} 

和XAML:

<ListBox x:Name="filesList" ItemsSource="{Binding Path=Names, Converter={StaticResource NamesListConverter}}" /> 

但列表框中的木珠更新(添加或删除)后不更新。
我已经注意到,如果我从绑定中删除转换器的作品完美。 我的代码有什么问题?

+0

您无法使用DynamicResource转换器。抛出异常 – user2348001 2013-05-04 09:46:34

回答

3

您的转换器正在从原始的ObservableCollection中的对象创建新的集合。使用绑定设置的ItemsSource不再是原始的ObservableCollection。 为了更好地理解,这等于你写的东西:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value == null) 
     return null; 
     var list = (value as ICollection<string>).Where((x) => x.StartsWith("A")).ToList(); 
     return list; 
    } 

该转换器返回的列表是从源收集数据的副本,新的对象。原始集合中的进一步更改不会反映在新列表中,因此ListBox不知道有关更改。 如果要过滤数据,请查看CollectionViewSource

编辑:如何筛选

 public ObservableCollection<string> Names { get; set; } 
    public ICollectionView View { get; set; } 
    public MainWindow() 
    { 
     InitializeComponent(); 

     Names= new ObservableCollection<string>(); 
     var viewSource = new CollectionViewSource(); 
     viewSource.Source=Names; 

     //Get the ICollectionView and set Filter 
     View = viewSource.View; 

     //Filter predicat, only items that start with "A" 
     View.Filter = o => o.ToString().StartsWith("A"); 

     DataContext=this; 
    } 

在XAML设置的ItemsSource为的CollectionView

<ListBox x:Name="filesList" ItemsSource="{Binding Path=View}"/> 
+0

谢谢!你可以请一个例子来满足我需要的东西? – user2348001 2013-05-04 09:57:02

+0

@ user2348001更新与过滤器的例子,应该没问题,但我从“内存”写道,也许有一些错误。 – jure 2013-05-04 10:08:54

+0

谢谢!但过滤器似乎没有更新,我改变了列表中现有的值 – user2348001 2013-05-04 12:21:00

0

也许当您添加或删除元素不使用转换器。实现你想要的最简单的方法可能是在你的类中实现INotifyPropertyChanged,并在每次添加或删除项目时触发PropertyChanged事件。 一般来说,“正确”的方法是使用CollectionView