【问题标题】:Windows Phone CollectionViewSort not showing anythingWindows Phone CollectionViewSource 不显示任何内容
【发布时间】: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&lt;MyItemViewModel&gt; 并让getter 返回_allItems,我的页面将显示预期的项目。我在这里做错了什么?

【问题讨论】:

    标签: c# xaml windows-phone-8 collectionviewsource


    【解决方案1】:

    问题在于LongListSelector 控件要求其ItemsSource 实现IList,而CollectionViewSource 不这样做。这意味着您不能将CollectionViewSource 绑定到开箱即用的LongListSelector。您可以通过尝试在代码隐藏文件中设置它来看到这一点,如下所示:

    myLongListSelector.ItemsSource = myCollectionViewSource.View;
    

    这给出了一个错误,说它无法将视图转换为IList

    我知道至少有两种解决方案,一种是围绕 CollectionViewSource 编写一个包装类,它确实实现了 IList 然后绑定到它。另一个问题给出了一个例子(我没有尝试过):LongListSelector grouping using CollectionView in Windows Phone 7 or Windows Phone 8

    另一种方法是不使用CollectionViewSource,而是使用System.Linq 进行排序,如本问题中建议的那样:How to Sort a LongListSelector in Windows Phone

    【讨论】:

    • 嗯。我对此一无所知。让我尝试其他修复之一。或者只使用 ItemsControl。
    猜你喜欢
    • 1970-01-01
    • 2012-09-29
    • 2020-11-10
    • 2012-04-12
    • 2019-11-11
    • 2017-09-25
    • 2012-08-02
    • 2019-08-11
    • 2018-06-25
    相关资源
    最近更新 更多