Windows phone 8 LongListMultiSelector动态选择项目

时间:2014-03-04 20:07:41

标签: windows-phone-8 longlistselector windows-phone-toolkit

如何动态地(在代码后面)在Windows Phone Toolkit的LongListMultiSelector中选择几个项目。 SelectedItems属性没有setter。

我的代码:

 private async void GetGenres()
    {
        var genres = await App.MusClient.GetGenresAsync();

        var preferencedGenresIdsList = App.GetFromIsoStorage<List<string>>(App.GENRES_IDS_KEY_STRING);

        GenresListBox.ItemsSource = genres;




        foreach (var item in GenresListBox.ItemsSource)
        {
            if (preferencedGenresIdsList.Contains(((Genre)item).Id))
            {
                LongListMultiSelectorItem container = GenresListBox.ContainerFromItem(item) as LongListMultiSelectorItem;
                if (container != null)
                {
                    container.IsSelected = true;
                }
            }
        }




        if (genres.Result == null || genres.Count == 0)
        {
            MessageBox.Show("No results available");
        }

    }

1 个答案:

答案 0 :(得分:1)

我找到了解决方案

private async void GetGenres()
    {
        var genres = await App.MusClient.GetGenresAsync();

        var preferencedGenresIdsList = App.GetFromIsoStorage<List<string>>(App.GENRES_IDS_KEY_STRING);

        GenresListBox.ItemsSource = genres;




        foreach (var item in GenresListBox.ItemsSource)
        {
            if (preferencedGenresIdsList.Contains(((Genre)item).Id))
            {
                GenresListBox.ScrollTo(item);
                LongListMultiSelectorItem container = GenresListBox.ContainerFromItem(item) as LongListMultiSelectorItem;
                if (container != null)
                {
                    container.IsSelected = true;
                }
            }
        }
        GenresListBox.ScrollTo(GenresListBox.ItemsSource[0]);



        if (genres.Result == null || genres.Count == 0)
        {
            MessageBox.Show("No results available");
        }

    }

它不起作用的原因是因为尚未在UI上创建项目。 GenresListBox.ScrollTo(项目); - 强制UI创建元素!