列表框 - 填充ItemsSource后无法选择第一个元素

时间:2014-04-22 06:30:08

标签: c# asynchronous async-await windows-phone-8.1 win-universal-app

我正在使用WP8.1并且我发现了我的列表框的行为 - 为了让我更容易重现,我放了the code here。设备和模拟器都会出现问题。

我有一个绑定到ObservableCollection的列表框,点击按钮时它会被项目填充:

public sealed partial class MainPage : Page
{
    List<string> populationOfItems = new List<string>();
    ObservableCollection<string> itemsToView = new ObservableCollection<string>();

    public MainPage()
    {
        this.InitializeComponent();

        second.Click += second_Click;
        myList.ItemsSource = itemsToView;
        // populate list of items to be copied
        for (int i = 0; i < 6; i++) populationOfItems.Add("Item " + i.ToString());
        BottomAppBar = new CommandBar();
    }

    private async void second_Click(object sender, RoutedEventArgs e)
    {
        itemsToView.Clear();
        await PopulateList();
    }

    private async Task PopulateList()
    {
        await Task.Delay(100); // without this line code seems to work ok
        itemsToView.Add("FIRSTELEMENT"); // add first differet element
        foreach (var item in populationOfItems)
            itemsToView.Add(item);
    }
}

我第一次填写清单时,一切正常(图1)。但是当我第二次按下按钮时,我可以看到元素不是从第一个而是从第二个(图2)。好的 - 它在上面,但我可以滚动到它,当我握住我的手指(鼠标)我可以滚动列表并看到它存在,但当我停止滚动列表隐藏(滚动到第二个元素)第一个元素。此外,当您选择任何项目时 - 当您握住手指时,列表看起来似乎没问题(图3),当您释放时,它会再次隐藏第一个元素。当您将列表向上/向下移动几次时,它会修复并正常工作。

重现问题的方法:

  • 点击第二个按钮 - 填写列表
  • 向下滚动列表,以便隐藏第一个元素(这很重要
  • 再次点击第二个按钮
  • 尝试向上滚动列表并查看第一个元素,释放手指

Pic.1 enter image description here

Pic.2 enter image description here

Pic.3 enter image description here

问题似乎与异步任务有关(这就是为什么我也异步标记了这个问题) - 没有行await Task.Delay(100);,代码似乎工作正常。

有人知道会出现什么问题吗?

编辑 - 其他一些尝试

我还尝试通过Dispatcher运行填充流程,但没有成功 - 问题就存在了。

我还尝试填充临时List(不是ObservableCollection),并且从async Task返回后,填充ObservableCollection - 问题仍然存在。

List<string> temporaryList = new List<string>();
private async Task PopulateList()
{
    await Task.Delay(100); // without this line code seems to work ok
    temporaryList.Clear();
    temporaryList.Add("FIRSTELEMENT"); // add first differet element
    foreach (var item in populationOfItems)
        temporaryList.Add(item);
}

private async void second_Click(object sender, RoutedEventArgs e)
{
    itemsToView.Clear();
    await PopulateList();
    foreach (var item in temporaryList)
       itemsToView.Add(item);
}

编辑2 - 在acync中创建的returnig列表任务也没有多大帮助:

private async void second_Click(object sender, RoutedEventArgs e)
{
    itemsToView.Clear();
    var items = await PopulateList();
    foreach (var item in items)
        itemsToView.Add(item);
}

private async Task<IEnumerable<string>> PopulateList()
{
    await Task.Delay(100); // without this line code seems to work ok
    List<string> temporaryList = new List<string>();
    temporaryList.Add("FIRSTELEMENT"); // add first differet element
    foreach (var item in populationOfItems)
        temporaryList.Add(item);
    return temporaryList;
}

编辑3 - 因为我检查了在Windows Phone 8.1下运行的相同代码,Silverlight可以正常运行。

1 个答案:

答案 0 :(得分:0)

您不应将UI处理与数据检索混合在一起,因为它们现在同时发生。

还要注意,当您调用await PopulateList()时,执行流程将返回到UI线程,并准备接受点击并触发点击事件。

请改为尝试:

private async void second_Click(object sender, RoutedEventArgs e)
{
    // UI thread
    var items = await PopulateListAsync(); // -> return to UI thread
    // back to UI thread
    itemsToView.Clear();
    itemsToView.Add("FIRSTELEMENT"); // add first differet element
    foreach (var item in items)
    {
        itemsToView.Add(item);
    }
}

private async Task<IEnumerable<string>> PopulateListAsync()
{
    // caller thread - UI thread
    await Task.Delay(100)
        .ConfigureAwait(continueOnCapturedContext: false);
    // some other thread
    return populationOfItems;
}

您可能想要阅读此内容:

修改

我相信这证明了你正在尝试做的事情。我已经添加了一些延迟,让您在手机上看到它。

<强> MainPage.xaml中

<phone:PhoneApplicationPage
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:System="clr-namespace:System;assembly=mscorlib"
    x:Class="PhoneApp1.MainPage"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
            <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <phone:LongListSelector x:Name="List" HorizontalAlignment="Stretch" Margin="0" VerticalAlignment="Stretch" ItemsSource="{Binding}" LayoutMode="List">
                <phone:LongListSelector.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" Style="{StaticResource PhoneTextExtraLargeStyle}" />
                    </DataTemplate>
                </phone:LongListSelector.ItemTemplate>
            </phone:LongListSelector>
            <Button Content="Button" Margin="0" Grid.Row="1" Click="Button_Click" x:Name="Button1"/>

        </Grid>
    </Grid>

</phone:PhoneApplicationPage>

<强> MainPage.xaml.cs中

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Phone.Controls;

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        private List<string> populationOfItems = new List<string>
        {
            "one",
            "two",
            "three",
            "four",
            "five"
        };
        private ObservableCollection<string> itemsToView = new ObservableCollection<string>();

        public MainPage()
        {
            InitializeComponent();
            this.DataContext = this.itemsToView;
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Button1.IsEnabled = false;
            var items = await PopulateListAsync();
            itemsToView.Clear();
            await Task.Delay(100);
            itemsToView.Add("FIRSTELEMENT");
            foreach (var item in items)
            {
                await Task.Delay(10);
                itemsToView.Add(item);
            }
            this.Button1.IsEnabled = true;
        }
        private async Task<IEnumerable<string>> PopulateListAsync()
        {
            await Task.Delay(100)
                .ConfigureAwait(continueOnCapturedContext: false);
            return populationOfItems;
        }
    }
}