如果在ViewModel构造函数中未填充ObservableCollection, ListView将不显示数据
本文关键字:ListView 数据 显示 ObservableCollection 填充 ViewModel 构造函数 如果 | 更新日期: 2023-09-27 18:12:15
如果viewmodel构造函数中没有加载ObservableCollection源,Listview将无法显示过滤器数据。
如果我在构造器中加载ObservableCollection源,然后过滤数据,那么一切都可以正常工作
我在这里错过了什么
XAML文件 <ListView ItemsSource="{Binding SourceList}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>>
<TextBox Text="{Binding foo.OrderID}">
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<TextBox Text="{Binding MyFilter, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
....
}
public class MyViewModel : ViewModelBase
{
public ICollectionView collectionView { get; set; }
public MyViewModel ()
{
repository = new Repository();
//Fill data
LoadData();
}
public void LoadData()
{
using (var context = new Context())
{
var query = (from o in Order
join p in Products on o.ProductID equals p.ProductID
select o);
listSourceData = new ObservableCollection<Foo>(query );
collectionView = CollectionViewSource.GetDefaultView(listSourceData)
as ICollectionView;
}
}
private ObservableCollection<Foo> listSourceData;
public ObservableCollection<Foo> SourceList
{
get
{
return listSourceData;
}
set
{
listSourceData = value;
RaisePropertyChanged();
}
}
private string _filterID;
public string MyFilter
{
get { return _filterID; }
set
{
_filterID= value;
// Approcah 1 which is working
FilterCollection();
// Approcah 2 which is not working
FilterCollectionWithSearchCriteria();
}
RaisePropertyChanged();
}
}
private void FilterCollection()
{
// apply filter which works ok as collectionview load in constructor
collectionView.Filter =...
}
private void FilterCollectionWithSearchCriteria()
{
//loadData method in constructor is commented
loadDataWithID(_filterID);
// in code I can see its filtered and showing object of Foo
collectionView.Filter =...
}
public void loadDataWithID(string _filterID)
{
using (var context = new Context())
{
var query = (from o in Order
join p in Products on o.ProductID equals p.ProductID
where o.OrderId==_filterID
select o);
listSourceData = new ObservableCollection<Foo>(query );
collectionView = CollectionViewSource.GetDefaultView(listSourceData)
as ICollectionView;
}
}
}
不要像这样在构造函数之外创建ObservableCollection
的新实例:
listSourceData = new ObservableCollection<Foo>(query);
如果您想首先清除集合中的所有项,请执行以下操作:
public void loadDataWithID(string _filterID)
{
using (var context = new Context())
{
var query = (from o in Order
join p in Products on o.ProductID equals p.ProductID
where o.OrderId==_filterID
select o);
SourceList.Clear();
SourceList.AddRange(query.ToList());
...
}
您应该设置公共属性(SourceList)而不是(listSourceData)的值,以便RaisePropertyChanged()工作