我正在尝试在 WP8 应用程序中开发一个页面,该页面的顶部有一个搜索框,以及与下面的搜索匹配的项目列表,并随着搜索框的更新而更新。很简单,对吧?但我无法让它工作。
仔细阅读 StackOverflow 和 interwebz 后,推荐的解决方案似乎是使用 CollectionViewSource
。好吧,我正在尝试使用它,但没有显示任何项目。一旦我切换到ObservableCollection
在 XAML 中包含我的项目,一切都显示正常。
我的数据是从数据库异步加载的。
XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<toolkit:PhoneTextBox Grid.Row="0" Hint="search query" ActionIcon="/Assets/Search.png" Text="{Binding SearchQuery, Mode=TwoWay}">
<i:Interaction.Behaviors>
<themes:TextBoxUpdateOnTextChangedBehavior />
</i:Interaction.Behaviors>
</toolkit:PhoneTextBox>
<phone:LongListSelector Grid.Row="1" ItemsSource="{Binding SearchResults}" />
<!-- I have also tried binding to SearchResults.View with no success -->
</Grid>
查看模型
public class MyViewModel
{
private ObservableCollection<MyItemViewModel> _allItems = new ObservableCollection<MyItemViewModel>();
public CollectionViewSource SearchResults { get; private set; }
public MyViewModel()
{
SearchResults = new CollectionViewSource { Source = _allItems };
_allItems.CollectionChanged += (_, __) => SearchResults.View.Refresh();
LoadAllItemsAsync();
}
private async void LoadAllItemsAsync()
{
IList<MyItemModel> models = await LoadMyModels();
_allItems.AddRange(models.Select(model => new MyItemViewModel(model)));
}
}
如您所见,我什至还没有尝试编写过滤代码。上面的代码不应该基本上显示一个包含我已加载的所有项目的 LongListSelector 吗?如果我更改 SearchResults
输入 ObservableCollection<MyItemViewModel>
并让 getter 返回 _allItems
,我的页面显示了预期的项目。我在这里做错了什么?
最佳答案
问题是 LongListSelector
控件要求其 ItemsSource
实现 IList
,而 CollectionViewSource 则不这样做。这意味着您无法立即将 CollectionViewSource
绑定(bind)到 LongListSelector
。您可以通过尝试在代码隐藏文件中设置它来看到这一点,如下所示:
myLongListSelector.ItemsSource = myCollectionViewSource.View;
这会出现错误,指出无法将 View 转换为 IList
。
我知道至少有两种解决方案,一种是围绕 CollectionViewSource 编写一个包装类,它实现 IList,然后绑定(bind)到它。另一个问题给出了一个例子(我没有尝试过):LongListSelector grouping using CollectionView in Windows Phone 7 or Windows Phone 8
另一种方法是不使用CollectionViewSource
,而是使用System.Linq
进行排序,如本问题中建议的:How to Sort a LongListSelector in Windows Phone
关于c# - Windows Phone CollectionViewSort 不显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22111601/