我是新來的ICollectionView,我目前正在嘗試過濾對象列表。將項目添加到ObservableCollection時更新ViewModel並傳遞過濾器<string>
這裏是我的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「SearchKeywords」,在列表中正確地更新,但到通知「OnPropertyChanged」添加項目不是叫。我怎樣才能做到這一點 ?
編輯:我添加了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);
}
}
當我添加關鍵字爲「_families.SearchKeywords」的ItemControle得到新的項目,但過濾器嘩嘩與視圖模型不適用。
OnPropertyChanged(「SearchKeywords」)不叫??你是什麼意思?如果放一個斷點它不會被打到?拋出錯誤?或者是什麼?請更具體 – Tuco
您的最終目標是什麼?它聽起來好像你正在得到你想要的行爲。爲什麼你需要激發'OnPropertyChanged'? –
@Tuco我更新了我的帖子 – Thibaud