【发布时间】:2017-08-09 15:57:48
【问题描述】:
我是 ICollectionView 的新手,目前正在尝试过滤对象列表。
这是我的视图模型:
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 部分和 Add 方法。
这是绑定 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>
这是方法
private void Kw_Add(object sender, RoutedEventArgs e)
{
if (!_families.SearchKeywords.Contains(this.Keywords.Text))
{
_families.SearchKeywords.Add(this.Keywords.Text);
}
}
当我将关键字添加到“_families.SearchKeywords”时,ItemControle 会获取新项目,但使用 ViewModel 的过滤器不适用。
【问题讨论】:
-
OnPropertyChanged("SearchKeywords") 没有被调用?...你是什么意思?如果放一个断点它不会被击中?抛出错误?要不然是啥?请更具体
-
你的最终目标是什么?这听起来就好像你得到了你想要的行为。为什么要开除
OnPropertyChanged? -
@Tuco 我更新了我的帖子