我是ICollectionView的新手,我正在尝试过滤对象列表。
这是我的ViewModel:
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<RevitFamily> _myData;
public ObservableCollection<RevitFamily> MyData
{
get { return _myData; }
}
string searchName = string.Empty;
ObservableCollection<string> searchKeywords = new ObservableCollection<string>();
public string SearchName
{
get { return searchName; }
set
{
searchName = value;
myDataView.Filter = FilterName;
OnPropertyChanged("SearchName");
}
}
public ObservableCollection<string> SearchKeywords
{
get { return searchKeywords; }
set
{
searchKeywords = value;
myDataView.Filter = FilterName;
OnPropertyChanged("SearchKeywords");
}
}
ICollectionView myDataView;
public ViewModel()
{
_myData = new ObservableCollection<RevitFamily>();
myDataView = CollectionViewSource.GetDefaultView(_myData);
//when the current selected changes store it in the CurrentSelectedPerson
myDataView.CurrentChanged += delegate
{
//stores the current selected person
CurrentSelectedFamily = (RevitFamily)myDataView.CurrentItem;
};
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
当我在ObservableCollection&#34; SearchKeywords&#34;中添加项目时,列表已正确更新,但通知&#34; OnPropertyChanged&#34;不打电话。我怎么能这样做?
编辑:我添加了XAML部分和添加方法。
这是绑定ObservableCollection的XAML代码。
<Border Grid.Row="6" Grid.ColumnSpan="3" Height="100">
<ItemsControl x:Name="ListKeywords" ItemsSource="{Binding SearchKeywords, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:CrossLabel MyLabel="{Binding}" Remove="Kw_Remove"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
这是Methode
private void Kw_Add(object sender, RoutedEventArgs e)
{
if (!_families.SearchKeywords.Contains(this.Keywords.Text))
{
_families.SearchKeywords.Add(this.Keywords.Text);
}
}
当我将关键字添加到&#34; _families.SearchKeywords&#34; ItemControle获取新项目,但过滤器威望与ViewModel不适用。
答案 0 :(得分:1)
只需在构造函数中订阅CollectionChanged
事件,无需每次都替换该集合。
public ViewModel()
{
searchKeywords.CollectionChanged += searchKeywords_CollectionChanged;
}
void searchKeywords_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
throw new NotImplementedException();
}
答案 1 :(得分:0)
将项目添加到ObservableCollection
会导致集合触发其CollectionChanged
事件。这与OnPropertyChanged
无关。您的SearchKeywords
属性属于ViewModel
类的属性 - 只有在您实际更改OnPropertyChanged
的值时才会调用SearchKeywords
方法,即替换ObservableCollection
1}}使用完全不同的ObservableCollection
。