【发布时间】:2014-03-01 07:37:57
【问题描述】:
我正在尝试在 WP8 应用程序中开发一个页面,该页面在顶部有一个搜索框和一个与下面的搜索匹配的项目列表,并随着搜索框的更新而更新。很简单,对吧?除非我不能让它工作。
在仔细阅读 StackOverflow 和 interwebz 之后,推荐的解决方案似乎是使用 CollectionViewSource。好吧,我正在尝试使用它,但没有显示任何项目。当我切换到包含我在 XAML 中的项目的 ObservableCollection 时,一切正常。
我的数据是从数据库异步加载的。
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,我的页面将显示预期的项目。我在这里做错了什么?
【问题讨论】:
标签: c# xaml windows-phone-8 collectionviewsource